I have 2 files, A.cpp and B.cpp, in a Win32 console application.
Both 2 files contain only the following 2 lines of code:
#include "stdafx.h" int k;
When compiling it produces the error
Error 1 error LNK2005: "int k" (?a@@3HA) already defined in A.obj
I don't understand what is happening.
Can someone please explain this to me?
Why this error?
You broke the one definition rule and hence the linking error.
Suggested Solutions:
If you need the same named variable in the two cpp files then You need to use Nameless namespace(Anonymous Namespace) to avoid the error.
namespace { int k; }
If you need to share the same variable across multiple files then you need to use extern
.
A.h
extern int k;
A.cpp
#include "A.h" int k = 0;
B.cpp
#include "A.h" //Use `k` anywhere in the file
In the Project’s Settings, add /FORCE:MULTIPLE
to the Linker’s Command Line options.
From MSDN: "Use /FORCE:MULTIPLE to create an output file whether or not LINK finds more than one definition for a symbol."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With