Eric Brunstad
Eric Brunstad

Reputation: 101

Why does 'x' have internal rather than external linkage?

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

Upvotes: 3

Views: 81

Answers (1)

Adam
Adam

Reputation: 17339

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

Upvotes: 5

Related Questions