error LNK2005, already defined?
c++
Solution
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
Problem
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?