0

Having 2 simple files like that:

Main.c:

#include "Initialization.cpp"
int main() {    
    return 0;
}

and Initialization.cpp:

int main2() {
    return 0;
}

I'm getting en error:

..."int __cdecl main2(void)" (?main2@@YAHXZ) already defined in Initialization.obj...

What's peculiar when i complied the program the first time everything was ok. After recompilation this error starts appearing.

PS. I'm using Visual Studio c++ 2019

Daros911
  • 435
  • 5
  • 14
  • 2
    Don't `#include` cpp files, only header files. Compile cpp files individually, and then link the resulting object files together to make the final executable. – Remy Lebeau Dec 24 '20 at 23:37
  • How did you compile? (compile command and what compiler version?) – Tony Tannous Dec 24 '20 at 23:38
  • The compiler sees `Main.c` as `int main2() { return 0; } int main() { return 0; }` after preprocessing. If you compile `Initialization.cpp` in addition to `Main.c`, this should explain, why `main2` is available from 2 object files... – fabian Dec 24 '20 at 23:40
  • @TonyTannous I'm using Visual Studio c++ 2019 as i've added in my question. – Daros911 Dec 24 '20 at 23:40
  • @fabian Ok, but Why does the first compile runs OK, while recompiling NOT? – Daros911 Dec 24 '20 at 23:43
  • Seems like some issue with your Makefile. If you just compile Main.c things should work. – user2233706 Dec 24 '20 at 23:49
  • Technically compiler shouldn't have a problem here. It's the linker that discovers these issues. Compiling `Main` as a C or C++ code seems to make a difference. Probably different name mangling saved you the first time... – fabian Dec 24 '20 at 23:52

1 Answers1

2

The preprocessor copies everything in the include file into Main.c which will look

int main2() {
    return 0;
}

int main() {    
    return 0;
}

Both Initialization.o and Main.o now have definition for main2(). Thus, you break the one definition rule and invoke undefined behavior.

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86