Undefined link when using extern

I have the following setup (hopefully this is not a very simple example):

hijras

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

a.cpp

MyClass inst;

Bh

#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?

+5
source share
4 answers

I know this question is old, but it may be useful for someone.

A global variable (in this case MyClass inst) should not be a externcompilation unit that defines it (here A.cpp)

One way to achieve this:

  • (, global.h) * cpp, .
  • extern , (, #ifdef):

global.h :

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

EXTERN MyClass inst;

A.h :

#ifndef A_H_
#define A_H_

// your header content (without globals)

#endif /* A_H_ */

A.cpp:

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

, !

+9

, , . , , , MyClass MyClassFunc.

MyClass , .

0

A.cpp

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

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

g++ A.o B.o
0
source

From the main code of the code you posted, I would say that you forgot #include <B.h>in your B.cpp file.

0
source

All Articles