What is the proper way of declaring variables in the header file in c++? And if it is not a good idea, then why? Thank you.
1 Answers
4
votes
The correct way would be to declare the variable with the extern keyword in the header file and then you have to declare it in one (!) cpp file without the extern keyword.
But:
Variables in header files are global variables. These have much problems. Here a few:
- You don't know in which order they are initialized. When one is a class and their constructor accesses another global variable, it is possible that this other global variable isn't initialized
- Global variables waste your namespace
- When you use global variables, you almost certainly don't use well-known and proven programming concepts (like modularity). Also your functions will have many side effects which makes your code hard to understand. In a few weeks you will no longer know, which functions will change which variables, and so on. Your code will be much more readable and understandable, if you stick to this concepts and don't use global variables.
You should never use global variables in C++. They are only there for backward compatibility with C.
extern
. whats is the reason for doing so? – Vis Vivaextern
can prevent a declaration from also being a definition but it has the same effect on declarations in header files as other source files. If you want to ask whatextern
is used for then make that your question; it would be less cryptic. – CB Baileyextern int k = 21;
is a perfectly good declaration and definition. – CB Bailey