Home > Article > Backend Development > Why am I getting the \"Error LNK2005: Multiple Definitions\" error in my Win32 console application?
Error LNK2005: Multiple Definitions
In a Win32 console application, you have two source files, A.cpp and B.cpp, each containing the following code:
<code class="cpp">#include "stdafx.h" int k;</code>
Upon compilation, an error is encountered:
Error 1 error LNK2005: "int k" (?a@@3HA) already defined in A.obj
Explanation:
This error stems from violating the one definition rule. In C , every global variable or function can only have a single definition across all translation units (source files). In your case, both A.cpp and B.cpp define the variable k, leading to multiple definitions and the linking error.
Solutions:
To resolve this issue, consider the following options:
1. Using Anonymous Namespace:
If you require the variable k to be used within both A.cpp and B.cpp but want to avoid external linkage, you can utilize an anonymous namespace:
<code class="cpp">namespace { int k; }</code>
2. Using extern:
If you need to share the variable k across multiple files, you should declare it as extern in a header file (A.h) and define it in one source file (e.g., A.cpp):
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` within B.cpp</code>
By following these solutions, you can avoid multiple definitions of k and successfully compile your application.
The above is the detailed content of Why am I getting the \"Error LNK2005: Multiple Definitions\" error in my Win32 console application?. For more information, please follow other related articles on the PHP Chinese website!