BillyJean
BillyJean

Reputation: 1577

restricting scope of variables in headers

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?

Upvotes: 0

Views: 134

Answers (3)

Andy Prowl
Andy Prowl

Reputation: 126412

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 static keyword to give those variables internal linkage and workaround the problem of multiple definitions. This way, however, each translation unit (.cpp file) 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 as static.

The normal practice here is either to leave those variable definitions in main(), or to have one header which contains only extern declarations 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.

Upvotes: 1

Baptiste Wicht
Baptiste Wicht

Reputation: 7663

If the variables you are talking about are global variables private to main, I think that you should let them in main.cpp. If they are not used anywhere else, it does not make sense to declare them in a header

You could also create a class implementing the "main" features with your variables in private scope so that they won't be used by other parts of the implementation .

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308101

The usual practice would be to go ahead and define them in main.cpp, since they're in a distinct block and won't affect the readability of the code. However you can certainly move them out to a separate include file that's only included in one .cpp, that's a stylistic choice that's completely up to you.

Upvotes: 1

Related Questions