Home >Backend Development >C++ >Why Am I Getting an 'Undefined Reference to Static Variable' Error in C ?

Why Am I Getting an 'Undefined Reference to Static Variable' Error in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-15 11:46:10956browse

Why Am I Getting an

Resolving "Undefined Reference to Static Variable" Error in C

When working with static class variables, you may encounter the "undefined reference to static variable" error in C . This article will explore the issue and provide a solution.

Consider the following code as an example:

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

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

Upon compiling this code, you may receive the error "undefined reference to 'Helloworld::x'". This is because you have not provided a definition for the static variable x.

In C , static class variables must be defined outside the class definition. Simply adding a definition for x in the global scope will resolve the error:

int Helloworld::x; // Define the static variable

You can initialize x with any appropriate value. If no initializer is provided, it will be zero-initialized by default.

Therefore, the modified code will look like this:

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

int Helloworld::x = 0; // Initialize the static variable

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

Now, the compiler will be able to correctly locate the definition of x and resolve the error. Remember, even though the foo() function is not static, it can still access the static variable x of the Helloworld class.

The above is the detailed content of Why Am I Getting an 'Undefined Reference to Static Variable' Error 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