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>
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!