-2

I have 2 files each containing a static int variable which has the same name :

test-1.cpp:

#include "test-2.cpp"

static int a;

int main() {

}

test-2.cpp:

static int a;

void fonction() {

}

When I compile with cl test-1.cpp on command line, I get this error:

test-1.cpp(3): error C2086: 'int a' : redefinition
holo
  • 331
  • 2
  • 13
  • 1
    You included one file into another (it's as if you've copied its source). So now you've file with two `static int a` definitions, which your compiler promptly report to you as error. You probably wanted to compile two files separately, not to include one file into another. – Radosław Cybulski Jun 14 '19 at 07:28
  • Yes but I want to use the "fonction" function in test-1.cpp... I realized I have to use headers. Thank you for your help ! – holo Jun 14 '19 at 07:51

3 Answers3

4

Because you include test2.cpp into test-1.cpp the actual code seen by the compiler is this:

static int a;

void fonction() {

}

static int a;

int main() {

}

Hence the redefinition.

The #include preprocessor command includes the file textually.

What you actually want is have both files test-1.cpp and test-2.cpp included into the Visual Studio project.

You want this:

test-1.cpp

#include "test-2.h"

static int a;

int main() {
  fonction();
}

test-2.cpp

#include "test-2.h"

static int a;

void fonction() {

}

test-2.h

void fonction();
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
3

Of course, you are #including test-2.cpp in test-1.cpp. It's as if you have only one file. If you remove the #include and do this command

cl test-1.cpp test-2.cpp

then it will work.

This whole area is called separate compilation and it's something that newbies struggle with (it's also not often taught very well). Because of separate compilation you should never include one cpp file in another cpp file. Instead you should hand both files to the compiler so they can be compiled separately.

If one cpp file needs to know what's defined in another cpp file, then create a header file with declarations of what's in the second cpp file and include that in the first cpp file.

john
  • 85,011
  • 4
  • 57
  • 81
1

In this line;

#include "test-2.cpp"

you tell the preprocessor to put the content of test-2.cpp into test-1.cpp. Hence you define static int a; twice. This is not allowed. To fix this, remove the #include.

Note that you need to carefully distinguish between declarations (which can occur many times) and definitions (which can occur only once). Have a look at this thread for more info.

lubgr
  • 37,368
  • 3
  • 66
  • 117
  • I still have to use ```#include``` but with a header file and not a cpp file... Thank you for your help and for the link ! – holo Jun 14 '19 at 07:50