2

Before marking this as duplicate, I've already tried the "common header + extern variable" method.

From link:

In A.cpp (or) B.cpp write,

int gVariable = 10;

Remember to write the above definition in only one source file or else linker will complain of multiple symbols if you write in both the source files.

And in the common header of A.cpp, B.cpp write,

extern int gVariable;

when I want to include B.cpp into A.cpp(use B.cpp functions in A.cpp) in this example, it won't work. An example is here

Thanks

unkownhihi
  • 27
  • 1
  • 5
  • 1
    `In A.cpp (or) B.cpp write, int gVariable = 10; Remember to write the above definition in only one source file` do you think you did that step properly? – KamilCuk Feb 13 '21 at 21:33

2 Answers2

3

You're using the same include guard in test.h and shared.h

#ifndef SHARED_H //
#define SHARED_H //

extern int testVar;
#endif /*SHARED_H*/

Also, you're not including test.h in test.cpp, nor actually defining testVar

#include "test.h"

int testVar = 0;

void toOne() {
    testVar = 1;
}

https://onlinegdb.com/vCXz53DtJ

KamilCuk has rigthly pointed out that symbols starting with double underscores are reserverd, so I also changed your include guards

Jack Lilhammers
  • 1,207
  • 7
  • 19
2

Three mistakes. You use the same include guard for both files

#ifndef __TEST_H

Make sure each header file has it's own include guard (typically named after the file).

Second mistake is that you failed to #include "shared.h" in test.cpp, so you get an error.

Third mistake (thanks Jack) is that despite what you claim in the question you fail to define testVar in either of your cpp files.

john
  • 85,011
  • 4
  • 57
  • 81