Home > Article > Backend Development > Why am I getting the \"error LNK2005: already defined?\" error when I define the same variable in multiple C files?
In your console application, you've encountered an unexpected error while compiling files A.cpp and B.cpp. Both files contain the following code:
#include "stdafx.h" int k;
However, the compilation process generates an error:
Error 1 error LNK2005: "int k" (?a@@3HA) already defined in A.obj
This error stems from the violation of the "one definition rule." In C , each variable, function, and object can only be defined once. In your case, you've defined the variable "k" in both A.cpp and B.cpp.
If you'd like to use the same named variable in both files, you can utilize a nameless namespace (anonymous namespace) to avoid the conflict.
namespace { int k; }
By encapsulating "k" within a namespace, you effectively limit its scope to the respective files, preventing the definition error.
If you intend to share the "k" variable across multiple files, you can employ the technique of external declaration and definition:
A.h (header file)
extern int k;
A.cpp
#include "A.h" int k = 0;
B.cpp
#include "A.h" // Use 'k' variable as needed
In this scenario, you declare a variable as external in A.h and define it in A.cpp. The B.cpp file only needs to include A.h to access the variable, avoiding the definition conflict.
The above is the detailed content of Why am I getting the \"error LNK2005: already defined?\" error when I define the same variable in multiple C files?. For more information, please follow other related articles on the PHP Chinese website!