在C++中,經常需要include一些自己定義的頭文件,如果處理不當,很容易出現"multipe definition ....."的錯誤。
閑話少說,先來一個例子:
假設定義了如下3個文件:global.h a.cpp b.cpp
//global.h: #ifndef _GLOBAL_H_ #define _GLOBAL_H_ const int a=1; int b; #endif
//a.cpp
#include <iostream> #include <stdlib.h> #include "global.h" using namespace std; void test1() { cout<<"test1"<<endl; }
//b.cpp
#include <iostream> #include <stdlib.h> #include "global.h" using namespace std; void test2() { cout<<"test2"<<endl; }
void main()
{
cout<<"hello world"<<endl;
}
編譯:g++ -o main test1.cpp test2.cpp
提示出現錯誤:multiple definition of b....
解決方法:
1. 要是b是一個常量的話,就直接定義成const int b;即可
2. 將b定義成static, 這樣在include “global.h” 的cpp中都能修改b