Error LNK2005: "int k" Already Defined
When linking a Win32 console application with multiple C files, an error "error LNK2005: "int k" (?a@@3HA) already defined in A.obj" may arise. This error occurs when a variable with the same name is defined in multiple files.
In the given example, both A.cpp and B.cpp define a variable k. According to the one definition rule, each global variable or function must have a single definition. Having multiple definitions leads to ambiguity and linking errors.
Solutions:
To resolve this error, you can use the following approaches:
Use Nameless Namespace (Anonymous Namespace):
If the variable k is intended to be private to each file, use a nameless namespace to prevent the symbol name collision.
<code class="cpp">namespace { int k; }</code>
This isolates the symbol k within each file, preventing other files from accessing or redefining it.
Declare and Define Variable in Separate Files:
If you need to share the variable k across multiple files, use extern to declare it in the header file and define it in a separate compilation unit.
A.h
<code class="cpp">extern int k;</code>
A.cpp
<code class="cpp">#include "A.h" int k = 0;</code>
B.cpp
<code class="cpp">#include "A.h" // Use `k` anywhere in the file</code>
By declaring k as extern in the header file, other files can access and use it without redefining it.
The above is the detailed content of Why Am I Getting \'Error LNK2005: \'int k\' Already Defined\' in My Win32 Console Application?. For more information, please follow other related articles on the PHP Chinese website!