Home >Backend Development >C++ >Why Do I Get 'Undefined Reference to Static Variable' Errors When Accessing Static Variables in C ?

Why Do I Get 'Undefined Reference to Static Variable' Errors When Accessing Static Variables in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-30 01:12:16403browse

Why Do I Get

Static Variable Referencing Issue in C

In C , accessing static variables within non-static class methods can lead to compilation errors if the static variable is not properly defined. One common error encountered is "undefined reference to static variable."

The Problem

Consider the following code snippet:

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

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

This code aims to access the static variable x from the non-static method foo(). However, compiling this code may result in the "undefined reference to static variable" error because the static variable x lacks a definition.

The Solution

The solution is to provide a definition for the static variable x outside the class definition. The definition can be added after the class definition, as shown below:

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

// Definition of static variable x
int Helloworld::x = 0; // Initialize x to 0 (or any appropriate value)

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

By defining the static variable x outside the class definition, the compiler can locate and allocate memory for x. Additionally, it is important to initialize the static variable to a specific value or allow it to be zero-initialized in the absence of an initializer.

With these modifications, the code will successfully compile and execute, allowing you to access the static variable x from non-static member functions of the Helloworld class.

The above is the detailed content of Why Do I Get 'Undefined Reference to Static Variable' Errors When Accessing Static Variables in C ?. 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