MrSnrub
MrSnrub

Reputation: 455

Why is Visual Studio giving a duplicate error even though I'm not explicitly including a source file?

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.

Upvotes: 0

Views: 279

Answers (2)

Jasper Kent
Jasper Kent

Reputation: 3676

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.

Upvotes: 4

NathanOliver
NathanOliver

Reputation: 180945

First, you never want to include a cpp file. The general way1 to structure your code is to put your declarations in one or more header files, and then have one cpp file for each header file. You then compile and link all of those cpp files together.

This is what Visual Studio does for you automatically. You create all of your header and cpp files in the project, and then it will compile each of those cpp files and then link the resulting object files together to build the executable. So, because both Main.cpp and File2.cpp have the same variable defined in them, you get a multiple definition error because both files are being compiled together.

1: unless you have templates

Upvotes: 2

Related Questions