**代碼:**
頭文件print_tools.h
****
~~~
#include<stdio.h>
void printStr(const char *pStr)
{
printf("%s\n",pStr);
}
void printtInt(const int i)
{
printf("%d\n",i);
}
~~~
頭文件counter.h
****
~~~
#include"print_tools.h"
static int sg_value;
void counter_init()
{
sg_value=0;
}
void counter_count()
{
sg_value++;
}
void counter_out_result()
{
printStr("the result is:");
printtInt(sg_value);
}
~~~
main.cpp
~~~
#include "print_tools.h"
#include "counter.h"
int main()
{
? char ch;
? counter_init();
? printStr("please input some charactors:");
? while((ch=getchar())!='$')
? ? {
? ? ? if(ch=='A')
counter_count();
? ? }
? counter_out_result();
}
~~~
**疑:**以上代碼編譯時有何問題嗎,是什么導致的呢?
解答:void printStr(const char*)和'void printtInt(int) 函數redefine了,道理很簡單,因為在counter.h中已包含了print_tools.h,在main.cpp中又包含了print_tools.h頭文件,也就是兩次包含了print_toosl.h,所以也就發生了重定義錯誤,這是初學者常見問題,要避免這個問題,我們必須采取防范措施,就是使用預編譯命令,如下作修改:
****
頭文件print_tools.h
****
~~~
#ifndef PRINT_TOOLS_H //如果未定義 PRINT_TOOLS_H
#define PRINT_TOOLS_H //則定義 然后編譯以下源代碼
#include<stdio.h>
void printStr(const char *pStr)
{
? printf("%s\n",pStr);
}
void printtInt(const int i)
{
? printf("%d\n",i);
}
#endif //結束 //如此改頭文件就只被編譯器編譯一次了,起到了防范重定義錯誤的作用
~~~
**頭文件counter.h**
****
~~~
#ifndef COUNTER_H //
#define COUNTER_H //
#include"print_tools.h"
static int sg_value;
void counter_init()
{
? sg_value=0;
}
void counter_count()
{
? sg_value++;
}
void counter_out_result()
{
? printStr("the result is:");
? printtInt(sg_value);
}
#endif //
~~~
在一個工程項目中頭文件眾多繁雜,采用這個方法可以很好的避免,所以每當我們定義一個頭文件時要養成如此的良好習慣。
======= welcome to my HomePage([*http://blog.csdn.net/zhanxinhang*](http://blog.csdn.net/zhanxinhang)) to have a?communication =======