简体   繁体   English

使用extern关键字在头文件中声明变量/ C ++

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

What is the proper way of declaring variables in the header file in c++? 在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. 正确的方法是在头文件中使用extern关键字声明变量,然后必须在一个没有extern关键字的(!)cpp文件中声明变量。

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++. 您永远不要在C ++中使用全局变量。 They are only there for backward compatibility with C. 它们仅是为了与C向后兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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