I'm using Visual Studio 2019. I create a new C++ console application. I have a file Main.cpp in my Source Files folder with the following code:
#include <iostream>
int i = 10;
int main()
{
std::cout << i << std::endl;
std::cin.get();
}
I create a second file in my Source Files folder called File2.cpp with only the following line:
int i = 2;
If I try to compile this code I get an error "one or more multiply defined symbols found". Why am I getting this error even though I have not explicitly done #include "File2.cpp"
in Main.cpp?
UPDATE: HOWEVER, if I remove File2.cpp and replace it instead with a file in my Header Files folder called File2.h (containing only one line: int i = 2
), and all other things being equal, it compiles fine. Similar to the previous example, the only difference is that instead of a second file being a .cpp Source file, it is now a .h Header file.
In C++, global variables (declared outside of any class) default to having external linkage. That's to say they are visible to other modules when the application is linked.
Thus both .cpp file expose a variable i
to the linker, which objects.
Four solutions:
1) Put one or both declarations in a different namespace:
namespace Wibble
{
int i = 2;
}
so they have different fully qualified names.
2) Declare one or both as static
:
static int i = 2;
which turns off the external linkage.
3) Put one or both in an anonymous namespace:
namespace
{
int i = 2;
}
which automatically assigns a unique namespace to each - effectively the same result as (2)
4) Declare all but one of them as extern
without initialization:
extern int i;
this says that the variable i
is actually the same variable as the one in the other file, which was no declared as extern
.