Home > Article > Backend Development > Why Does Setting a Static Field from the Main Method Cause an \"Unresolved External Symbol\" Error?
Unresolved External Symbol Error: Setting Static Field from Main Method
When trying to update a static field in a class from the main method, developers may encounter the error "LNK2001: unresolved external symbol." This error occurs because of a specific rule that requires static class members to be defined outside the class definition for proper linking.
Consider the following code:
<code class="cpp">class A { public: A() { /* Implementation */ } }; class B { public: static A* a; }; int main() { B::a = new A; // Attempting to set the static field }</code>
In this code, we attempt to set the static field a of class B to a new A object from the main method. However, the compiler will throw the "LNK2001" error because the definition of a is missing.
According to the C standard, declarations of static data members within class definitions are not considered definitions. Instead, the definitions must be provided outside the class in a namespace scope using the class name and :: operator. Here's the corrected code:
<code class="cpp">class A { public: A() { /* Implementation */ } }; class B { public: static A* a; // Declaration }; // Definition of static field outside the class A* B::a; int main() { B::a = new A; // Setting the static field }</code>
By defining a outside the class, the compiler can properly link the symbol and allow the static field to be modified from the main method.
The above is the detailed content of Why Does Setting a Static Field from the Main Method Cause an \"Unresolved External Symbol\" Error?. For more information, please follow other related articles on the PHP Chinese website!