我有两个文件中的代码:
Static.cpp:
static int s_Variable = 5;
Main.cpp:
extern int s_Variable;
我得到这个错误:
Build started...
1>------ Build started: Project: HelloWorld, Configuration: Debug Win32 ------
1>Static.cpp
1>Main.obj : error LNK2001: unresolved external symbol "int s_Variable" (?s_Variable@@3HA)
1>E:Visual Studio 2019DevCPPSeriesHelloWorldbinWin32DebugHelloWorld.exe : fatal error LNK1120: 1 unresolved externals
1>Done building project "HelloWorld.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
在每个文件上都可以正确编译,所以我知道这只是一个链接问题。到底出了什么问题?
静态全局变量没有外部链接;从某种意义上说,它们是"本地的"。到一个给定的翻译单元。如果您想在单独的翻译单元中引用它,则必须使用非静态全局变量。