问题描述
linux上的编译器g ++
file.h有以下内容,int x = 5;
并且在主程序文件中我可以访问 X"没有声明它
extern x。程序编译并运行正常....
程序编译并运行正常,x声明为extern。
所以有必要如果没有
声明它是extern,那么将x声明为extern?什么是标准和良好做法?
compiler g++ on linux
file.h has the following, int x=5;
and inside the main program file I can access "x" without declaring it
"extern x". Program compiles and runs fine....
also program compiles and runs fine with x declared as extern.
So is it necessary to declare x as extern if one get away without
declaring it extern ? What is the standard and good practice ?
推荐答案
好的做法是将''x'的非定义声明放入
头文件
extern int x; //注意:这里没有初始化程序
并将定义放入一个(并且只有一个)实现文件中
int x = 5 ;
当然,另一个好的做法是避免全局变量,除非
它们确实是必要的。
-
祝你好运,
Andrey Tarasevich
The good practice is to put a non-defining declaration of ''x'' into the
header file
extern int x; // Note: no initializer here
and put the definition into one (and only one) of the implementation files
int x = 5;
Of course, another good practice is to avoid global variables unless
they are really necessary.
--
Best regards,
Andrey Tarasevich
作为Andrey说,把extern int x;在.h文件中,
*和*" int x = 5;"在* .cpp文件的* *中。
-
Andre Heinen
我的地址是a dot heinen在europeanlink dot com"
As Andrey said, put "extern int x;" in the .h file,
*and* "int x = 5;" in *one* of the .cpp files.
--
Andre Heinen
My address is "a dot heinen at europeanlink dot com"
这篇关于关于extern的问题?..的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!