Undefined Reference to Static Variable in C
When working with static variables in C , developers often encounter the error "undefined reference to static variable." This article explores this issue and provides a solution without using a static method.
Problem:
Consider the following code:
1 2 3 4 5 6 7 8 |
|
This code triggers an "undefined reference" error because the static variable x is referenced in a non-static method foo(), but it lacks a definition.
Solution:
To resolve this issue, it is essential to provide a definition for the static member variable x outside the class definition. This can be achieved as follows:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
By specifying the initial value as 0 or leaving it undefined, x will be zero-initialized. Alternatively, a more appropriate initial value can be assigned.
The above is the detailed content of Why Do I Get an 'Undefined Reference to Static Variable' Error in C and How Can I Fix It Without Using Static Methods?. For more information, please follow other related articles on the PHP Chinese website!