I have two .cpp file written before which has different functions. Now,I have a problem. I want to use these two functions in the .cpp files written before to be part of my new program. However, I cannot simply use #include<dp.cpp>
to achieve this goal.
I believe there must be some means which can fulfill the demand, but I wonder whether I should use a header file or something else.
Please help me if you can solve the problem or have some inspiring suggestions.
Put the function prototypes in a header file and include that header file wherever you need to use those functions. Also, be sure to include that header file in the source file that you declare the functions in.
Sure. You'll need to add a new .h file to your project. Here's an example with a couple of functions. Add and subtract, for the sake of ease and example.
example.h
1 2 3 4
// File: example.h
int Add(int a, int b);
int Subtract(int a, int b);
example.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13
// File: example.cpp
#include "example.h"
int Add(int a, int b)
{
return a+b;
}
int Subtract(int a, int b)
{
return a-b;
}
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// File: main.cpp
#include <iostream>
#include "example.h"
usingnamespace std;
int main()
{
int a = 10;
int b = 5;
int result = Add(a,b);
cout << "Addition result = " << result << endl;
result = Subtract(a,b);
cout << "Subtraction result = " << result << endl;
return 0;
}