【问题标题】:code guards fail代码保护失败
【发布时间】:2011-07-23 23:23:04
【问题描述】:

获取这些文件:

啊。

#ifndef A_H
#define A_H

char EL[] = "el";
#endif

a.cpp

#include "a.h"

b.h

#ifndef B_H
#define B_H

#include "a.h"

#endif

b.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

为什么以及如何解决?

【问题讨论】:

标签: c++ c linker-errors include-guards multiple-definition-error


【解决方案1】:

如果您将定义包含在多个翻译单元中,则包含保护并不能保护您免受定义一个对象的影响!

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

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

【讨论】:

  • 我需要在标题中定义它,因为我需要用文字字符串专门化一个模板。喜欢:typedef SimpleParticleDecorator<11, EL, true, false> ElectronDecorator;
  • 把它作为一个单独的问题发布,我们来看看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-31
相关资源
最近更新 更多