3

Based on my reading of the C++ 2011 spec, I would think that the following code would create a variable 'x' with external linkage in file1.cc. I would think that I would be able to access that variable from main.cc and therefore that the program would print 'x'. However, I instead get a linker error for an undefined reference to 'x' from main.cc. Why does 'x' from file1.cc have internal linkage? I think the compiler is interpreting section 3.5.3 as giving 'x' internal linkage in file1.cc. However I have not "explicitly declared" 'x' to be 'const', as that section would require. I am using g++ version 4.6.3.

main.cc:

#include <iostream>

typedef const char CC;

extern CC x[];

int main(void) {
  std::cout << x[0] << std::endl;
}

file1.cc:

typedef const char CC;

CC x[] = "abc";
  • With gcc-4.8.2 and clang-3.3 and `-std=c++11` both I get an undefined symbol error. The reason is given in [this question](http://stackoverflow.com/questions/998425/why-does-const-imply-internal-linkage-in-c-when-it-doesnt-in-c) – vonbrand Feb 27 '14 at 02:00

1 Answers1

5

The const makes all the difference. In C++ const variables declared at file scope implicitly have internal linkage. This is because in C++ const values can be used as compile-time constants (which leave nothing to link to).

See this answer.

You can add extern to your definition in file1.cc to explicitly specify external linkage for x:

extern CC x[] = "abc";
Community
  • 1
  • 1
Adam
  • 16,808
  • 7
  • 52
  • 98