Home > Backend Development > C++ > Why Am I Getting \'Unresolved External Symbol\' Error When Setting a Static Field in C ?

Why Am I Getting \'Unresolved External Symbol\' Error When Setting a Static Field in C ?

Susan Sarandon
Release: 2024-11-01 01:35:28
Original
179 people have browsed it

Why Am I Getting

Unresolved External Symbol for Static Object Field

This article investigates the error message "error LNK2001: unresolved external symbol" encountered when attempting to set a static field in a class from the main method.

In the provided code snippet, the declaration of the static field "a" in class "B" occurs within the class definition itself. However, according to the C standard, such declarations are not considered definitions. For static data members, the proper definition must appear outside the class in the enclosing namespace scope, using the "::" operator.

The rule that governs this requirement is known as the One Definition Rule (ODR), which mandates that every entity (including static data members) have a single unique definition in the entire program. This rule ensures that there is no ambiguity regarding the value of the static member.

Therefore, to resolve the error, the code should be modified as follows, where "a" is defined in the namespace scope:

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

    }
};

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

A* B::a; // Definition in namespace scope

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

By explicitly defining the static member outside the class, the linker can correctly resolve the symbol reference and the code will compile successfully.

The above is the detailed content of Why Am I Getting \'Unresolved External Symbol\' Error When Setting a Static Field 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template