I found this: How do I use extern to share variables between source files? and its main answer is rather clear to me.
However I do not understand why this gives me an error:
x.h :
#pragma once namespace x { class A { public: void func() const; }; // extern A const a; // cannot move this out of the include file !!! // extern int xi; // fine to remove from here } --- main.cpp ---
#include "stdafx.h" #include "x.h" namespace x { extern int xi; extern const A a ; } // instead of include file extern int i; int _tmain(int argc, _TCHAR* argv[]) { std::cout << i << std::endl; // works std::cout << x::xi << std::endl; // works x::a.func(); return 0; } --- x.cpp ---
#include "stdafx.h" #include "x.h" namespace x { void A::func() const { std::cout << "x::A::func() called" << std::endl; } const A a; // Problem if const int xi = 234; // works } int i = 123; // works error LNK2001: unresolved external symbol "class x::A const x::a" (?a@x@@3VA@1@B)
(VisualStudio 2013) Compiling the two files is fine, and I can build and run it if I remove the const keyword, or if I move the extern statement into the include file.
Thanks for an explanation (can't believe in a compiler bug) ;)
extern A const a;(in x.h) andextern const A a ;(in main.cpp) are the same thing.