code guards fail

2019-08-07 10:05发布

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条回答
霸刀☆藐视天下
2楼-- · 2019-08-07 10:38

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

查看更多
登录 后发表回答