c++ - static 和 extern 关键字 LINK 错误 C++

标签 c++ static extern

我编写了程序来测试 C++ 中的 staticextern 关键字。

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/

相关文章:

c++ - 如何在 Linux (redhat) 上使用 xterm 中的 valgrind 和 gdb?

android - 使用静态方法创建 AlertDialog?

c - union 内部的 2 个结构,来自头文件

c - 存储类声明

c++ - 在多台机器上分布状态

c++ - 是否可以在编译时计算数字阶乘,但没有枚举

C++ MySQL 准备语句

reactjs - gatsby 中的静态文件图像路径

c++ - gcc 4之后C++中的线程安全单例?

c++ - 如何将指向 SDL_Surface 的 "global"指针传递给 C++ 中类的渲染函数?