Home >Backend Development >C++ >Why Do I Get an 'Undefined Reference to Static Variable' Error in C and How Can I Fix It Without Using Static Methods?

Why Do I Get an 'Undefined Reference to Static Variable' Error in C and How Can I Fix It Without Using Static Methods?

Barbara Streisand
Barbara StreisandOriginal
2024-12-19 16:03:09829browse

Why Do I Get an

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:

class Helloworld {
  public:
     static int x;
     void foo();
};
void Helloworld::foo() {
     Helloworld::x = 10;
};

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:

class Helloworld {
  public:
     static int x;
     void foo();
};

// Define the static variable outside the class
int Helloworld::x = 0;

void Helloworld::foo() {
     Helloworld::x = 10;
};

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn