Search code examples
c++librariesextern

error: multiple definition of... when defining an extern variable in a third library


I have three libraries:

The first (Lib.h) declares a variable that will be defined elsewhere:

extern int a;

The second one (Lib2.h) includes the third one:

#include "Lib3.h"

The .cpp file of this library (Lib2.cpp) contains nothing besides this:

#include "Lib2.h"

and the third (Lib3.h) finally contains the definition of the variable:

int a;

The main program simply includes the first and second library:

#include "Lib.h"
#include "Lib2.h"

When I compile the main program, I get the error mentioned.

What is the problem here?


Solution

  • When int a; exists in Lib3.h, then every translation unit that includes Lib3.h (directly or indirectly) will get its own copy of a, hence the error. a needs to be declared in Lib3.h as extern, just like it is in Lib.h, and then the actual int a; variable needs to be defined in a .cpp file elsewhere (Lib2.cpp will suffice) so there is only 1 copy of a that all of the externs refer to.