code guards fail

北慕城南 提交于 2019-12-11 08:59:19

问题


Take this files:

a.h

#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() { }

This is only an example, but I've really this problem:

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

why and how to solve?


回答1:


Include guards don't protect you against defining an object multiple times if you include the definition in multiple translation units!

As a solution, never define things in headers, but only declare them:

// header
extern char EL[2];

// TU
#include "header.h"
char EL[2] = "el";

// Other consumer
#include "header.h";
// can now use EL

(There are exceptions, of course; e.g. class definitions are fine (but class member function definitions are not (but inlined ones are)) -- beware.)


I should add that alternatively you can say static in your header file to make the definition private to each TU:

// header
static char EL[] = "EL";  // every TU gets a copy

(In C++0x you cannot use objects of static linkage as template parameters, though.)



来源:https://stackoverflow.com/questions/6803918/code-guards-fail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!