Home > Backend Development > C++ > body text

Why Does \'Unresolved External Symbol\' Occur When Setting Static Fields in C ?

DDD
Release: 2024-10-31 13:45:02
Original
780 people have browsed it

Why Does

Unresolved External Symbol: Understanding Static Field Declarations

When attempting to set a static field in one class to a different value from within the main method, you may encounter the error "unresolved external symbol" (error LNK2001: unresolved external symbol). This typically occurs if the static field is not properly initialized outside of the class definition.

According to the C reference, a declaration of a static data member inside a class definition is considered a declaration, not a definition. To define the static field, it must be declared outside the class definition, in a namespace scope enclosing the class definition.

For example, consider the following code:

<code class="cpp">class A
{
public:
    A()
    {

    }
};

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

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

In this case, the static field B::a is declared within the class definition, but not defined. To resolve this error, you must move the definition of the static field outside the class definition, as shown below:

<code class="cpp">class A
{
public:
    A()
    {

    }
};

class B
{
public:
};

// Static field definition outside the class
A* B::a = nullptr;

int main()
{
    B::a = new A;  // No error
}</code>
Copy after login

This change ensures that the static field is properly defined and can be used within the main method. By following the One Definition Rule, you can prevent "unresolved external symbol" errors and ensure that your static fields are correctly linked.

The above is the detailed content of Why Does \'Unresolved External Symbol\' Occur When Setting Static Fields in C ?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!