0

Good morning, Dear. I have the following configurations: -Visual Studio (C++14 by default).

//main.cpp
#include "funciones.cpp"
int main() {
    myMsj();

    return 0;
}

//funciones.cpp
#include <iostream>
//Declaration
void myMsj(void);

//Definition
void myMsj(void) {
    std::cout << "llamada desde main\n";
}

The compiler output: Gravedad Código Descripción Proyecto Archivo Línea Estado suprimido Error LNK2005 ya se definió "void __cdecl myMsj(void)" (?myMsj@@YAXXZ) en funciones.obj prueba-1 C:...\prueba-1\main.obj 1

Error LNK1169 se encontraron uno o más símbolos definidos simultáneamente prueba-1 C:...\prueba-1\x64\Debug\prueba-1.exe 1


I would like to clarify the following: *This code compiled me Correctly in IDE Code::Block.

I don't compile in Visual Studio and Eclipse C/C++. Why is this happening, dear? Am I doing something that declaration/definition/call that is already deprecated in VSC/Eclipse?

Thanks in advance.

OBI
  • 11
  • 7
    `#include "funciones.cpp"` is a big no-no. Never include a cpp file. – NathanOliver Nov 14 '22 at 16:06
  • 1
    To fix this 1: create a header and put `void myMsj(void);` in it. 2: include this header from your 2 cpp files. – drescherjm Nov 14 '22 at 16:09
  • Fixed! As @NathaOliver mentioned: "Don't include the .cpp's, only include the .h's. My confusion arose because Code::block did compile correctly. I had a mistake in the theory. Thanks again. – OBI Nov 14 '22 at 16:55
  • ***My confusion arose because Code::block did compile correctly*** My guess is that the `funciones.cpp` file was not part of your Code::Blocks project. Many IDEs require you to add the source files you create to the project by using some menu item in the IDE. Just putting the files in the same folder as the project is not enough. – drescherjm Nov 14 '22 at 17:17

1 Answers1

-1

The linker is complaining that it finds two definitions of the myHsj() function. This is probably because you are compiling both main.cpp and funciones.cpp, and then linking them together. Because in main.cpp you also include funciones.cpp, the compiler sees both main.cpp and funciones.cpp containing the myHsj() function.

The custom in C++ is to have a file called funciones.hpp (a so-called header file) that contains the function declaration, but not the definition. Then, both funciones.cpp and main.cpp can include funciones.hpp, while only funciones.cpp contains the definition. That should fix the error.

Kees-Jan
  • 518
  • 4
  • 16