Coding with Cpp: Linker complains about missing global variable - keymanapp/keyman GitHub Wiki
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
constin unit x.cpp - no
externdeclaration is visible for the global variable in unit x.cpp - the same global variable is referenced in a second unit y.cpp
externdeclaration 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.