The linker tells you that you have the variable k
defined multiple times. Indeed, you have a definition in A.cpp and another in B.cpp. Both compilation units produce a corresponding object file that the linker uses to create your program. The problem is that in your case the linker does not know whic definition of k
to use. In C++ you can have only one defintion of the same construct (variable, type, function).
To fix it, you will have to decide what your goal is
k
, you can use an anonymous namespace in both .cpp files, then refer to k
as you are doing now:.
namespace {
int k;
}
k
s to something else, thus avoiding the duplicate defintion.k
and use that in both .cpp files, you need to declare in one as extern int k;
, and leave it as it is in the other. This will tell the linker to use the one definition (the unchanged version) in both cases -- extern
implies that the variable is defined in another compilation unit.