undefined reference when using extern
Asked Answered
M

4

12

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?

Mcavoy answered 7/9, 2010 at 12:4 Comment(2)
Do you #include the definition of class MyClass in B.cpp?Bagman
You should include the full compiler error message in your post.Vulvitis
M
18

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!

Musa answered 17/7, 2013 at 8:22 Comment(0)
T
0

This is too bare an example to work out what's going on. However, based on the above it's entirely possible that when it hits the failing line the compiler has no knowledge of what's actually in MyClass and therefore cannot resolve MyClassFunc.

We would need to see the definition of MyClass and know where it is to answer for sure.

Telepathy answered 7/9, 2010 at 12:11 Comment(0)
M
0

You have to compile the above mentioned file A.cpp as

g++ -c A.cpp
g++ -c B.cpp

and then while creating the executable you should write the command as follows:

g++ A.o B.o
Multilingual answered 7/9, 2010 at 12:12 Comment(1)
Or in one step, g++ A.cpp B.cpp.Spokesman
V
0

From the basic example code you posted I'd say you've forgotten to #include <B.h> in your B.cpp file.

Vulvitis answered 7/9, 2010 at 12:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.