外部变量 - 多个文件
Extern Variable - Multiple Files
当我在另一个不同类型的文件中重新定义 extern
变量时,VS 编译器没有给出错误消息。据我所知,它应该引发错误,因为它在另一个文件中被全局定义为 extern
。这种行为的原因是什么?
source1.cpp
extern int x;
source2.cpp
int x = 5;
test.cpp
#include <iostream>
double x = 455;
int main()
{
std::cout << x; // writes 455
}
One and only one definition of every non-inline function or variable that is odr-used (see below) is required to appear in the entire program (including any standard and user-defined libraries). The compiler is not required to diagnose this violation, but the behavior of the program that violates it is undefined.
当我在另一个不同类型的文件中重新定义 extern
变量时,VS 编译器没有给出错误消息。据我所知,它应该引发错误,因为它在另一个文件中被全局定义为 extern
。这种行为的原因是什么?
source1.cpp
extern int x;
source2.cpp
int x = 5;
test.cpp
#include <iostream>
double x = 455;
int main()
{
std::cout << x; // writes 455
}
One and only one definition of every non-inline function or variable that is odr-used (see below) is required to appear in the entire program (including any standard and user-defined libraries). The compiler is not required to diagnose this violation, but the behavior of the program that violates it is undefined.