1

I was having some trouble with "multiple definitions" errors and found this solution that highlights the need to use the extern keyword.

Here is the example used to explain the solution.

FileA.h

#ifndef FILEA_H_
#define FILEA_H_
#include "FileB.h"
void hello();

#endif /* FILEA_H_ */

FileB.cpp

#include "FileB.h"

int wat = 0;

void world()
{
    //more code;
}

FileB.h

#ifndef FILEB_H_
#define FILEB_H_

extern int wat;  // The solution makes this change with the definition being in FileB.cpp
void world();


#endif /* FILEB_H_ */

Essentially, extern is needed to let the compiler know that wat is defined elsewhere in the code, and to avoid wat being declared multiple times when FileB.h is included multiple times.

MY QUESTION IS, how would wat be declared multiple times without the extern keyword? Specifically, the use of

#ifndef FILEB_H_
#define FILEB_H_

should be enough to avoid multiple definitions, as these header guards would prevent FileB.h from executing more than once. I tried it myself and the extern keyword IS needed to avoid errors. Does it have something to do with the linker? Hopefully this question makes sense.

  • 1
    Header guards do not protect against multiple sources defining the same variable causing a violation of the ODR. – drescherjm Oct 23 '20 at 17:10
  • The include guard is enough to prevent multiple definitions _per c++ source file_. The problem in your linked example comes from having two _different_ `c++` source files, `FileA.cpp` and `FileB.cpp`, that both indirectly include the declaration `int wat;` So today's lesson is: Never declare data in a `#include` file without the `extern` keyword. – TonyK Oct 23 '20 at 18:17
  • Wow, I never realized that header guards only prevent multiple definitions within a single source file. Thanks for the helpful responses! – reid-sutherland Oct 23 '20 at 22:52

0 Answers0