简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM