-
-
Notifications
You must be signed in to change notification settings - Fork 130
Coding with Cpp: Linker complains about missing global variable
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
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
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.
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.
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.