简体   繁体   English

为什么'x'有内部联系而不是外部联系?

[英]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. 基于我对C ++ 2011规范的阅读,我认为以下代码将在file1.cc中创建一个带有外部链接的变量“x”。 I would think that I would be able to access that variable from main.cc and therefore that the program would print 'x'. 我认为我可以从main.cc访问该变量,因此该程序将打印'x'。 However, I instead get a linker error for an undefined reference to 'x' from main.cc. 但是,我从main.cc获取了对'x'的未定义引用的链接器错误。 Why does 'x' from file1.cc have internal linkage? 为什么file1.cc中的'x'有内部链接? I think the compiler is interpreting section 3.5.3 as giving 'x' internal linkage in file1.cc. 我认为编译器将第3.5.3节解释为在file1.cc中给出'x'内部链接。 However I have not "explicitly declared" 'x' to be 'const', as that section would require. 但是我没有“明确声明”'x'是'const',因为该部分需要。 I am using g++ version 4.6.3. 我正在使用g ++版本4.6.3。

main.cc: main.cc:

#include <iostream>

typedef const char CC;

extern CC x[];

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

file1.cc: file1.cc:

typedef const char CC;

CC x[] = "abc";

The const makes all the difference. const使一切变得不同。 In C++ const variables declared at file scope implicitly have internal linkage. 在C ++中,在文件范围内声明的const变量隐式具有内部链接。 This is because in C++ const values can be used as compile-time constants (which leave nothing to link to). 这是因为在C ++中,const值可以用作编译时常量(不留任何东西链接)。

See this answer . 看到这个答案

You can add extern to your definition in file1.cc to explicitly specify external linkage for x : 您可以在file1.cc中为您的定义添加extern ,以明确指定x外部链接:

extern CC x[] = "abc";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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