Static Variable Link Error [Duplicate]
In C programming, a link error can occur when a static variable is declared but not defined in the code. This error indicates that the linker cannot find the definition of the static variable during the linking phase.
In the given code, the class Log has a static variable theString declared in the header file Log.h, but it is not defined in the implementation file Log.cpp. To resolve the link error, the static variable must be defined in the implementation file.
The corrected code in Log.cpp should be:
#include "Log.h" #include <ostream> string Log::theString; // Define the static variable here void Log::method(string arg) { theString = "hola"; cout << theString << endl; }
Additionally, it is recommended to remove the using namespace std; line from the header file. This practice prevents polluting the global namespace with std symbols, which can lead to naming conflicts and potential errors.
The above is the detailed content of Why Am I Getting a Static Variable Link Error in C ?. For more information, please follow other related articles on the PHP Chinese website!