0
votes

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
Can you clarify what you mean by "the proper way"? If you need a declaration for a variable in a header file then you just put a declaration in a header file. The fact that you want to put it in a header file doesn't make a difference to the syntax that you should use.CB Bailey
i have been told that i should use extern. whats is the reason for doing so?Vis Viva
@Abdulai: In some contexts adding adding extern 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 what extern is used for then make that your question; it would be less cryptic.CB Bailey
the extern keyword says to the compiler: Don't allocate memory for this variable, you will find it in another file. So you need one cpp file where the variable is declared without the extern keyword and all other files accessing it have to declare it with extern.Heinzi
@Heinzi: No it doesn't mean that. E.g. extern int k = 21; is a perfectly good declaration and definition.CB Bailey

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.