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

Community
  • 1
  • 1
datafiddler
  • 1,755
  • 3
  • 17
  • 30

1 Answers1

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

T.C.
  • 133,968
  • 17
  • 288
  • 421