简介: C++ "multiple definition of .. first defined here" 在C++中,有时候需要在不同文件中使用同一个变量。对于这类变量如果处理不当,很容易出现“multiple definition of... first defined here”的错误。
问题一般出在include上!
例如,定义了如下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
提示错误为:
[chris@zz jojo]g++ -o main a.cpp b.cpp
/tmp/ccc7OcsO.o:(.bss+0x0): multiple definition of `b'
/tmp/ccs7q2VA.o:(.bss+0x0):第一次在此定义
出错原因:a.cpp和b.cpp先分别被编译为.o格式的目标文件,两个目标文件再被链接器链接起来,这当中a.cpp和b.cpp分别进行了一次include“global.h”,相当于global.h中的代码重复出现了一次。因为a是const类型,所以重新定义也没事;但是b只是普通变量,重复定义显然不行。
显然,一个解决办法是把b定义为const int类型。或者,定义成static int类型也行。