Unveiling the Mystery of Error LNK2005: Understanding Multiple Definitions
When working with multiple C files within a project, the "error LNK2005, already defined" message can be a perplexing hindrance. This error signifies that multiple definitions of the same variable or function exist within the project. To delve into this issue, let's examine a specific example.
The Problematic Scenario
Consider a Win32 console application comprising two files: A.cpp and B.cpp. Both files contain only the following:
#include "stdafx.h" int k;
Upon compilation, the error arises:
Error 1 error LNK2005: "int k" (?a@@3HA) already defined in A.obj
The Root of the Problem: Violating the One Definition Rule
The fundamental principle underlying this error is the "one definition rule" (ODR) enforced in C . This rule dictates that any variable or function can only have one definitive definition throughout the entire project. In this scenario, both A.cpp and B.cpp attempt to define the same variable 'k', violating the ODR. As a result, the linker encounters a conflict and triggers the error message.
Addressing the Issue
To resolve this error, you can employ two primary approaches:
Approach 1: Utilizing Nameless Namespaces
If your intention is to share the same variable across multiple translation units (i.e., cpp files), consider utilizing a nameless namespace. A nameless namespace encapsulates the variable within its own scope, rendering it inaccessible outside that scope.
namespace { int k; }
Approach 2: External Variables
Alternatively, if you need to share a variable across multiple files but want to maintain its accessibility to external code, employ the 'extern' keyword. This approach involves declaring the variable in a header file (e.g., A.h):
extern int k;
and subsequently defining it in one of the implementation files (e.g., A.cpp):
#include "A.h" int k = 0;
The above is the detailed content of Why am I Getting \'error LNK2005: already defined\' in my C project?. For more information, please follow other related articles on the PHP Chinese website!