Home > Backend Development > C++ > Why Do I Get an 'Undefined Reference' Error When Accessing a Static Variable in a C Non-Static Method?

Why Do I Get an 'Undefined Reference' Error When Accessing a Static Variable in a C Non-Static Method?

DDD
Release: 2024-12-15 15:36:11
Original
335 people have browsed it

Why Do I Get an

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;
};
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template