使用 C++ 编译器进行外部初始化时出错
error in extern initialization with C++ compiler
我写了下面的代码
#include<iostream>
using namespace std;
extern int var = 0;
int main(void)
{
var = 10;
return 0;
}
我用过
g++ -std=c++11 test.cpp -o test
和
g++ test.cpp -o test
编译代码。我收到以下警告
test.cpp:44:12: warning: 'extern' variable has an initializer [-Wextern-initializer]
extern int var = 0;
^
1 warning generated.
这是什么意思?我需要为此担心吗?我怎样才能避免它?非常感谢~
One explanation 外部:
The extern keyword tells the compiler that a variable is declared in another source module (outside of the current scope). The linker then finds this actual declaration and sets up the extern variable to point to the correct location. Variables described by extern statements will not have any space allocated for them, as they should be properly defined elsewhere. If a variable is declared extern, and the linker finds no actual declaration of it, it will throw an "Unresolved external symbol" error.
既然是在别处声明的,那别处就是初始化它的地方。
更简单地说,如果你在单文件程序中声明它就足够了;删除外部短语。
我写了下面的代码
#include<iostream>
using namespace std;
extern int var = 0;
int main(void)
{
var = 10;
return 0;
}
我用过
g++ -std=c++11 test.cpp -o test
和
g++ test.cpp -o test
编译代码。我收到以下警告
test.cpp:44:12: warning: 'extern' variable has an initializer [-Wextern-initializer]
extern int var = 0;
^
1 warning generated.
这是什么意思?我需要为此担心吗?我怎样才能避免它?非常感谢~
One explanation 外部:
The extern keyword tells the compiler that a variable is declared in another source module (outside of the current scope). The linker then finds this actual declaration and sets up the extern variable to point to the correct location. Variables described by extern statements will not have any space allocated for them, as they should be properly defined elsewhere. If a variable is declared extern, and the linker finds no actual declaration of it, it will throw an "Unresolved external symbol" error.
既然是在别处声明的,那别处就是初始化它的地方。
更简单地说,如果你在单文件程序中声明它就足够了;删除外部短语。