简体   繁体   中英

using extern keyword to declare variables in header files / c++

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM