Skip to content

Coding with Cpp: Linker complains about missing global variable

sze2st edited this page Oct 28, 2025 · 2 revisions

Problem

You will get an unintended linker error LNK2001 for a global variable if all of the following holds:

  • the global variable is defined as const in unit x.cpp
  • no extern declaration is visible for the global variable in unit x.cpp
  • the same global variable is referenced in a second unit y.cpp
  • extern declaration is visible in unit y.cpp

Reason

C++ Compiler of Visual Studio limits the scope of the const global variable to unit x.cpp (maybe it is caused by specific kind of mangling). Hence it is not provided for usage in unit y.cpp

Note

The linker error is limited to global variables defined as const. Without const the global variable is visible in both units x.cpp and y.cpp.

Fix

extern declaration must be visible even in unit x.cpp. Hence provide extern declaration in header file and include it in both x.cpp and y.cpp.

Pitfall

Providing another definition of the global variable even in unit y.cpp will fix the linker error. However y.cpp will then use its own global variable which is different from the one of x.cpp.

Clone this wiki locally