Undefined Reference to Static Variable in C
When attempting to access a static variable within a non-static method of a class, developers may encounter the "undefined reference" error. To resolve this issue, it is important to provide a definition for the static variable outside the class declaration.
In the code snippet provided:
class Helloworld{ public: static int x; void foo(); }; void Helloworld::foo(){ Helloworld::x = 10; };
The static variable x is declared within the class but lacks a definition. To address this, we can add the following line outside the class definition:
int Helloworld::x;
This provides a definition for x, allowing the foo() method to access it without encountering an undefined reference error. It is important to note that the default value for static variables is zero, so an explicit initializer can be provided as desired.
By following these steps, developers can effectively access static variables within non-static methods, ensuring proper code functionality and avoiding undefined reference errors.
The above is the detailed content of Why Do I Get an 'Undefined Reference' Error When Accessing a Static Variable in a C Non-Static Method?. For more information, please follow other related articles on the PHP Chinese website!