Home > Backend Development > C++ > Why Does Setting a Static Field from the Main Method Cause an \'Unresolved External Symbol\' Error?

Why Does Setting a Static Field from the Main Method Cause an \'Unresolved External Symbol\' Error?

Linda Hamilton
Release: 2024-10-31 06:33:02
Original
875 people have browsed it

Why Does Setting a Static Field from the Main Method Cause an

Unresolved External Symbol Error: Setting Static Field from Main Method

When trying to update a static field in a class from the main method, developers may encounter the error "LNK2001: unresolved external symbol." This error occurs because of a specific rule that requires static class members to be defined outside the class definition for proper linking.

Consider the following code:

<code class="cpp">class A
{
public:
    A() { /* Implementation */ }
};

class B
{
public:
    static A* a;
};

int main()
{
    B::a = new A; // Attempting to set the static field
}</code>
Copy after login

In this code, we attempt to set the static field a of class B to a new A object from the main method. However, the compiler will throw the "LNK2001" error because the definition of a is missing.

According to the C standard, declarations of static data members within class definitions are not considered definitions. Instead, the definitions must be provided outside the class in a namespace scope using the class name and :: operator. Here's the corrected code:

<code class="cpp">class A
{
public:
    A() { /* Implementation */ }
};

class B
{
public:
    static A* a; // Declaration
};

// Definition of static field outside the class
A* B::a;

int main()
{
    B::a = new A; // Setting the static field
}</code>
Copy after login

By defining a outside the class, the compiler can properly link the symbol and allow the static field to be modified from the main method.

The above is the detailed content of Why Does Setting a Static Field from the Main Method Cause an \'Unresolved External Symbol\' Error?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template