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:
class A
{
public:
A()
{
}
};
class B
{
public:
static A* a;
};
A* B::a; // Definition in namespace scope
int main()
{
B::a = new A;
}
By explicitly defining the static member outside the class, the linker can correctly resolve the symbol reference and the code will compile successfully.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3