例如,定义了如下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 a.cpp b.cpp
提示错误为:
出错原因:a.cpp和b.cpp先分别被编译为.o格式的目标文件,两个目标文件再被链接器链接起来,这当中a.cpp和b.cpp分别进行了一次include“global.h”,相当于global.h中的代码重复出现了一次。因为a是const类型,所以重新定义也没事;但是b只是普通变量,重复定义显然不行。
显然,一个解决办法是把b定义为const int类型。或者,定义成static int类型也行。