我编写了程序来测试 C++ 中的 static 和 extern 关键字。
source1.cpp
#include "Header.h"
using namespace std;
static int num;
int main(){
num = 1;
cout << num << endl;
func();
}
source2.cpp
#include "Header.h"
using namespace std;
extern int num;
void func(){
num = 100;
cout << num << endl;
}
Header.h
#ifndef HEADER_H
#define HEADER_H
#include <iostream>
void func();
#endif
当我编译这个程序时,它给我一个链接错误。
error LNK2001, LNk1120 unresolved externals.
导致此链接错误的原因是什么?
最佳答案
此链接错误是因为 num 变量声明为 static 变量。
即使变量 num 在 source2.cpp 文件中声明为 extern,链接器也找不到它,因为它已被声明为 static 在 source1.cpp 中。
当您将变量声明为静态时,它是文件的本地变量;它具有文件作用域。该变量在此文件之外不可用。
关于c++ - static 和 extern 关键字 LINK 错误 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32285776/