Home >Backend Development >C++ >Why Does Accessing a Static Class Variable from a Non-Static Method in C Cause an Undefined Reference?
Accessing Static Class Variable from Non-Static Method
In C , when encountering an undefined reference to a static variable, such as in the given code snippet, the issue usually lies in the lack of a definition for that variable.
In the example provided, where the code attempts to access the static variable x from within the non-static method foo, it's important to note that foo is not a static function. Therefore, to resolve this issue, a definition for Helloworld::x must be provided outside of the class definition.
int Helloworld::x = 0; // Provide an initial value or leave uninitialized
Once the static variable is defined, the non-static method foo can access and modify it without requiring foo to be static itself.
void Helloworld::foo() { Helloworld::x = 10; }
By providing a definition for the static member variable, the compiler can locate its memory address and resolve the undefined reference.
The above is the detailed content of Why Does Accessing a Static Class Variable from a Non-Static Method in C Cause an Undefined Reference?. For more information, please follow other related articles on the PHP Chinese website!