Home > Article > Backend Development > How Do I Resolve the \"Unresolved External Symbol\" Error When Assigning to a Static Object Field?
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>
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)
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>
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!