1

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) ;)

2
  • 1
    I'm not too familiar with C++, but I don't think extern A const a; (in x.h) and extern const A a ; (in main.cpp) are the same thing. Commented Jun 3, 2015 at 16:29
  • @ColonelThirtyTwo: Why's that? Commented Jun 3, 2015 at 17:14

1 Answer 1

3

Namespace-scope const variables default to internal linkage (i.e., visible only within that translation unit). The extern is needed to override the default and give it external linkage (so that it can be accessed from a different translation unit).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.