undefined reference when using extern

21,898

I know this question is old, but it still might be helpful for someone.

The global variable (here: MyClass inst) should not be extern for the compilation unit which define it (here: A.cpp)

One way to achieve this:

  • declare your global variable in a separate header (let's say global.h) and include this header in the *cpp using these.
  • remove the extern keyword for the compilation unit which define them (e.g. with #ifdef) :

global.h looks like:

#ifdef A_H_
  #define EXTERN
#else
  #define EXTERN extern
#endif

EXTERN MyClass inst;

while A.h looks like:

#ifndef A_H_
#define A_H_

// your header content (without globals)

#endif /* A_H_ */

and A.cpp:

#include "A.h"
#include "global.h" // after A.h inclusion, we need A_H_ definition

Hope it helps!

Share:
21,898
Amir Rachum
Author by

Amir Rachum

Programmer, Board Gamer, Geek. Blog, Resume and Projects: http://amir.rachum.com/blog Twitter: @AmirRachum

Updated on July 17, 2020

Comments

  • Amir Rachum
    Amir Rachum almost 4 years

    I have the following setup (hopefully this is not too bare an example):

    A.h

    typedef std::map<unsigned int, float> MyClass;
    extern MyClass inst;
    

    A.cpp

    MyClass inst;
    

    B.h

    #include <A.h>
    void foo();
    

    B.cpp

    #include <B.h>
    void foo {
        inst.myClassFunc();
    }
    

    Now, when I use inst in B.cpp I get undefined reference to inst.

    Any idea on how to fix this?

  • Mike Seymour
    Mike Seymour over 13 years
    Or in one step, g++ A.cpp B.cpp.