0
votes

Why cant I access the variable value defined in the file.cpp file. Assuming it is linked with 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. Can extern be propagated in chain of headers like this

1) file.h

extern int value;

2)file.cpp

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

3) header1.h

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

4) main.cpp

#include "header1.h"
int main(char *argv[], int args) {
int result = value*10;      
    return result;
}
1
Exactly what error do you get? Are you sure objects from both file.cpp and main.cpp are given to the linker?aschepler

1 Answers

1
votes

Yes, extern can be propagated in this way. The compiler only needs to see that the variable is declared extern at the point of usage it doesn't matter through which header. 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.