I have a multi-file program consisting of
main.cpp
ext1.cpp
ext2.cpp
ext3.cpp
vars.h
As the name suggests, main.cpp is the main file, extX.cpp contains various functions and vars.h some global constants.
However, in main.cpp there are also (a few!) variable declarations, but they must only be within the scope of main.cpp — that is why I haven’t placed them in vars.h
I want to reduce the amount of code in main.cpp (for clarity-issues). I am looking for a way to declare these variables inside a header of some sort, but in a way that it is only visible to main.cpp.
Is it correctly understood that if I place them all inside e.g. vars_main.h (with no external keyword) and just include “vars_main.h”, then I have achieved my goal?
Is it considered to be “correct” C++-style to do it this way?
If those variables are used only in
main(), then yes, you could do that. But I would not go as far as considering it a “correct C++ style”.If one day you will end up including that header file into another translation unit (maybe because you will need to share just one of those variables), the linker will start complaining about multiple definitions.
At that point, to overcome this, you could use the
statickeyword to give those variables internal linkage and workaround the problem of multiple definitions. This way, however, each translation unit (.cppfile) will hold its own copy of those variables, which is probably not what you want, especially if they are not constant – just for the record, global constants have internal linkage by default, so you won’t need to explicitly qualify them asstatic.The normal practice here is either to leave those variable definitions in
main(), or to have one header which contains onlyexterndeclarations of those variables, and one translation unit that contains their definitions. Then, all the files which need to access those variable would just import the header with the declarations.