简体   繁体   English

头文件层次结构中的extern变量

[英]extern variable in hierachy of header file

Why cant I access the variable value defined in the file.cpp file. 为什么我不能访问file.cpp文件中定义的变量值。 Assuming it is linked with main. 假设它与main链接。 Tricky part is that the variable value is included indirectly. 棘手的部分是变量值被间接包括在内。 Main function includes header1.h which in return includes file.h which has variable value as extern. 主要功能包括header1.h,而后者又包含具有可变值extern的file.h。 Can extern be propagated in chain of headers like this extern可以像这样在标头链中传播

1) file.h 1)file.h

extern int value;

2)file.cpp 2)文件.cpp

#include "file.h"
int value = 25;

3) header1.h 3)header1.h

#include "file.h"
const int const_value = 100;

4) main.cpp 4)main.cpp

#include "header1.h"
int main(char *argv[], int args) {
int result = value*10;      
    return result;
}

Yes, extern can be propagated in this way. 是的, extern可以通过这种方式传播。 The compiler only needs to see that the variable is declared extern at the point of usage it doesn't matter through which header. 编译器只需要查看变量在使用时被声明为extern ,那么通过哪个标头就无关紧要。 The content of the header files are merely pasted at the top of source file by the pre-processor. 头文件的内容仅由预处理器粘贴到源文件的顶部。 So the compiler doesn't even know of header files. 因此,编译器甚至不知道头文件。

However, it is good idea that you should include all the header files required for the compilation of the source file independently in that header file. 但是,最好将所有编译源文件所需的头文件都单独包含在该头文件中。 It is much more easier to maintain such code. 维护这样的代码要容易得多。

Simply, include file.h in main.cpp and it will be much more intuitive for readers of your code. 只需在main.cpp包含file.h ,这对于您的代码阅读者将更加直观。

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

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