1

拿这个文件:

#ifndef A_H
#define A_H

char EL[] = "el";
#endif

a.cpp

#include "a.h"

bh

#ifndef B_H
#define B_H

#include "a.h"

#endif

b.cpp

#include "b.h"

主文件

#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

为什么以及如何解决?

4

1 回答 1

8

如果您将定义包含在多个翻译单元中,则包含守卫不会保护您避免多次定义对象!

作为一种解决方案,永远不要在标题中定义东西,而只声明它们:

// 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 中,您不能使用静态链接对象作为模板参数。)

于 2011-07-23T23:26:49.000 回答