0
votes

i am doing some example programs in VC++ 6.0 . For some simple and small programs i dont want to create separate project for each of the program . i have 2 files created in a single project and there is no .h file , so i have included .cpp file into another .cpp file . If i compile its working but if i build the code its giving error . Following is the code :

file1.cpp :
-----------

#include <iostream>
#include "Calculate_Int.cpp"
using namespace std;

int main ()
{
    cout << "\n\nFirst file \n" ;

    int x= cal_integer();

    return 0;

}


Calculate_Int.cpp:
------------------

#include<iostream>
using std::cout;
using std::endl;

int cal_integer(){
    cout<< 1+2<<endl;
    cout<<1-5<<endl;
    cout<<1-2<<endl;

        return 0;
}

If i build this Project1.exe following is the error :

Linking... Calculate_Int.obj : error LNK2005: "int __cdecl cal_integer(void)" (?cal_integer@@YAHXZ) already defined in file_1.obj Debug/Project_1.exe : fatal error LNK1169: one or more multiply defined symbols found Error executing link.exe.

Project_1.exe - 2 error(s), 0 warning(s)

Please let me know what is wrong .

1

1 Answers

0
votes

Including a file is the same as copying the contents of that file in the point you are including it. This means that the contents of Calculate_Int.cpp are compiled twice in your project. And this is what the linker error is telling you: it does not know which version to choose.

In order to compile main.cpp you just need to know the signature of the functions you are using there; this is, you just need a declaration, not a definition. So you can replace this line in main.cpp:

#include "Calculate_Int.cpp"

with this:

int cal_integer();

And your project will compile and link just fine. Anyway, the right way would be to create a file Calculate_Int.h with that line and include it anywhere you need it.