获取以下文件:
a.h
#ifndef A_H
#define A_H
char EL[] = "el";
#endifa.cpp
#include "a.h"b.h
#ifndef B_H
#define B_H
#include "a.h"
#endifb.cpp
#include "b.h"main.cpp
#include "b.h"
#include "a.h"
int main() { }这只是一个例子,但我确实遇到了这个问题:
g++ -c a.cpp
g++ -c b.cpp
g++ -c main.cpp
g++ -o main main.o a.o b.o
a.o:(.data+0x0): multiple definition of `EL'
main.o:(.data+0x0): first defined here
b.o:(.data+0x0): multiple definition of `EL'
main.o:(.data+0x0): first defined here
collect2: ld returned 1 exit status为什么以及如何解决?
发布于 2011-07-24 07:26:49
如果您在多个翻译单元中包含定义,则包含保护不能防止您多次定义对象!
作为一种解决方案,永远不要在headers中定义东西,而是只声明它们:
// header
extern char EL[2];
// TU
#include "header.h"
char EL[2] = "el";
// Other consumer
#include "header.h";
// can now use EL(当然,也有例外;例如,类定义很好(但类成员函数定义不是(但内联函数定义是)) --请注意。
我应该补充说,或者您可以在头文件中指定static,以使定义成为每个TU的私有定义:
// header
static char EL[] = "EL"; // every TU gets a copy(但在C++0x中,不能将静态链接的对象用作模板参数。)
https://stackoverflow.com/questions/6803918
复制相似问题