Home > Backend Development > C++ > body text

How Do I Resolve the \'Unresolved External Symbol\' Error When Assigning to a Static Object Field?

Patricia Arquette
Release: 2024-10-31 16:03:18
Original
715 people have browsed it

How Do I Resolve the

Understanding "Unresolved External Symbol" Error for Static Object Field Assignment

When writing code, you may encounter situations where you need to assign a value to a static object field from a different class. However, attempting such an assignment may lead to a linking error with the message "unresolved external symbol."

Consider a simplified code example:

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

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

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

Attempting to compile this code will result in the error:

error LNK2001: unresolved external symbol "public:
static class A * B::a" (?a@B@@2PAVA@@A)
Copy after login

This error occurs because static object fields are not implicitly defined in their class declarations. According to the C reference standard, "Declaration of a static data member inside a class definition is not a definition and may be of an incomplete type."

Rule for Definition of Static Object Fields

To resolve this error, you must explicitly define the static object field outside the class definition. This rule applies to all static object fields, regardless of their accessibility or mutability.

Example Definition:

<code class="cpp">A* B::a = nullptr;</code>
Copy after login

Placing the definition in the enclosing namespace scope ensures that the linker can find the symbol when attempting to resolve the assignment in main().

The above is the detailed content of How Do I Resolve the \'Unresolved External Symbol\' Error When Assigning to a Static Object Field?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!