Undefined Reference to Static Variable: Resolving Link Errors
When compiling C code, you may encounter a "Undefined symbols" error when referencing a static variable defined in a header file. This error occurs because the linker cannot find the definition of the static variable during linking.
In the example provided, the header file Log.h declares a static string member theString. However, the definition of this static variable is missing from the Log.cpp file. To resolve this issue, follow these steps:
Define the Static Variable in the CPP File:
#include "Log.h" #include <iostream> // Define the static variable here string Log::theString; void Log::method(string arg) { theString = "hola"; cout << theString << endl; }
Remove Unnecessary Namespace Declaration:
By making these changes, the linker will be able to find the definition of the static variable during linking, resolving the "Undefined symbols" error.
The above is the detailed content of Why Does My C Code Get an 'Undefined Reference to Static Variable' Linker Error?. For more information, please follow other related articles on the PHP Chinese website!