title: C++: Linking extern variables from within a namespace
body: <p>I can't seem to reference an externally-defined variable from within a namespace using <code>extern</code>.  It works from the global scope, but as soon as a namespace is thrown in there,  it fails to link.  </p>
  
  <p>My constants file looks like:</p>
  
  <p><code>StringConstants.cpp</code></p>
  
  <pre><code>#include "MyString.h"
  
  MyString test1("string1");
  
  MyString test2("string2");
  </code></pre>
  
  <p>The main program looks like this:</p>
  
  <p><code>main.cpp</code></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include "MyString.h"
  
  extern MyString test1;
  
  namespace {
      extern MyString test2;
  }
  
  int main(void) {
      printf("%s\n", test1.Str());
      printf("%s\n", test2.Str());
  }
  </code></pre>
  
  <p>I get similar errors in both GCC and Visual Studio:</p>
  
  <pre><code>gcc    main.o StringConstants.o   -o main
  main.o:main.cpp:(.text+0x49): undefined reference to `(anonymous namespace)::test2'
  collect2: ld returned 1 exit status
  
  1&gt;Linking...
  1&gt;main.obj : error LNK2001: unresolved external symbol "class MyString `anonymous namespace'::test2" (?test2@?A0x0df4aa01@@3VMyString@@A)
  1&gt;C:\p4\namespace_repro\namespace_repro2\Debug\namespace_repro2.exe : fatal error LNK1120: 1 unresolved externals
  </code></pre>
  
  <p>I tried qualifying the reference to test2 (<code>extern MyString ::test2</code>), but it just thinks that test2 is a static member of MyString.  A named namespace doesn't behave differently than an anonymous one.  For various reasons, we don't want to remove namespaces or put the externs outside of the namespaces.</p>
  
  <p>Here's the other files, for completeness:</p>
  
  <p><code>MyString.h</code></p>
  
  <pre><code>class MyString {
  public:
     MyString(const char* str): mStr(str) {};
     const char* Str() const { return mStr; }
  private:
     const char* mStr; 
  };
  </code></pre>
  
  <p><code>Makefile</code></p>
  
  <pre><code>CC=gcc 
  CFLAGS=-Wall
  
  main: StringConstants.o main.o
  </code></pre>
  
  <p>The goals for this system are that the constants all be defined in one file, and that they be resolved at link time rather than being in a header.  It seemed like the above code would work, but since it's rejected by two different linkers it seems my understanding of C++ is not good enough.  Advice on how to get this to work, other than putting the externs outside of the namespaces?</p>