Question:
Procedure to use one .cpp file in another .cpp file.?
Elroy
2012-08-27 22:03:33 UTC
There are two files, main.cpp and add.cpp file. The code of the two are as follows:
main.cpp
#include
#include
int add(int x,int y);
void main()
{
clrscr();
int a,b;
cout<<"Enter two nos. ";
cin>>a>>b;
cout<<"Required result is "<getch();
}

add.cpp
int add(int x,int y)
{
return (x+y);
}

I want to run the "main.cpp" file and get the answer of addition. I want to know what else have I to include.Thank you
Four answers:
Enna
2012-08-27 22:15:51 UTC
Solution: SWITCH TO C#!
peteams
2012-08-28 06:25:12 UTC
What you should really do is remove from main.cpp the line:



int add(int x, int y);



and place it in a file called add.h.



Both main.cpp and add.cpp should then have the additional line added (after the other #include lines):



#include "add.h"



That means both the code in main.cpp and add.cpp will see the add(x,y) forward reference. main.cpp will simply use it to create an external reference, while add.cpp will supply it as an implementation. The linker will wire the two up correctly.



Your #include statements should use "double-quotes" to enclose the file name rather than , "double-quotes" say "look for this file in the current directory and, if it is not found there, go look in the standard places" whereas say "just look in the standard places for this".
Anas Imtiaz
2012-08-28 07:46:29 UTC
You cannot directly insert a .cpp file into another. You will first have to create a header file i.e. a new library and define your function under that header file. Header files have extension .h After this, you can include that header file in your .cpp An example doing that is:



//Header file add.h



class add{

public: int add(int x, int y) { return x+y;}

};



//your main.cpp file

#include "add.h"



int main()

{

add number;

int sum = number.add(2, 3);

//rest of your code

return 0;

}



This is how you do it. If you have any queries, email or IM me.
Rana
2012-08-28 05:09:30 UTC
#include "add.cpp"

then call the "add" function inside the main.cpp.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...