为什么在全局范围内使用"extern int a"似乎不行?
Why does it seem not OK to using "extern int a" in global scope?
main.cpp
#include <iostream>
#include "test.h"
int a = 999;
int main() {
std::cout << a << std::endl;
printa();
return 0;
}
测试.h
#include <iostream>
extern const int a;
void printa(void) {
std::cout << a << std::endl;
}
当编译和运行时,它工作良好
但当我把main.cpp改成时
#include <iostream>
#include "test.h"
extern int a = 999; //here is the change, I have added extern
int main() {
std::cout << a << std::endl;
printa();
return 0;
}
效果不错,但会出现警告。
警告:初始化并声明的
怎么了为什么在全局范围内使用"extern int a"似乎不合适
怎么了?
没有错本身(因此是警告,而不是错误(。但是你给编译器的信息有冲突:
extern
告诉编译器,"这是在其他地方定义的,让链接器处理它"。
= 999
告诉编译器,"它在这里被(定义和(初始化为具有值999
"。
编译器在这一点上有效地忽略了extern
,并警告您信息存在冲突。
为什么在全局范围内使用"extern int a"似乎不合适?
实际上是"OK">。在您的头中,您的变量在全局范围内声明为extern
,并且一切都很好。
- 当您想要初始化变量时,不必重复
extern
关键字。此时(在.cpp中(该变量已被称为extern
,因为在包含标头时已经执行了声明 - 正如评论中提到的@Jarod42,您的常量声明和非常量初始化不匹配
- 如果在声明
extern
变量时对其进行初始化,则extern
将过时。extern
的语义是"好的,我把初始化推迟到其他地方"。因此发出警告
例如:
.h
extern int a; // declaration, as extern (will be initialized somewhere else)
extern const int b; // example with const
.cpp
int a = 42; // initialization
const int b = 4422; // initialization
相关文章:
- Visual Studio 2015:Extern "C" 和 "export" 关键字
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- Extern "C"错误在'int'之前'asm'或'__attribute__'
- C++ - extern int (double)
- 为什么"extern int &c;"工作正常?
- 超能力 NDK 安卓:返回 int 在"extern"块中成功,在调用函数中失败
- 无法为extern c int _clrcall生成pinvoke ..呼叫元数据中缺少的约定
- C++当"extern int * name"引用不存在的变量,然后访问"name"时会发生什么
- 警告(不合时宜):将 void(*)(int) 分配给 extern "C" void(*)(int)
- 如何使用extern关键字正确初始化struct[int]
- 为什么"extern const int n;"不能按预期工作?