how do i connect different files together?

I created a new file and put a function inside and i call in from the main.cpp file but it keeps telling me that there is a undefined reference.i even compiled and linked it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
add.cpp
int add(int x,int y){
    return x+y;
}


main.cpp
#include <iostream>

using namespace std;

int add(int x,int y);

int main()
{
    cout << "Hello world!" << endl;
    cout<<add(1,2);
    return 0;
}
Last edited on
Did you mean to do this as a class? Have you looked in the project folder to see if those files are there? And I'm still newbie to this stuff, but usually don't you also need a #include "_____", when including files?
this depends on your tools. It could be a 'project' (visual studio) or a makefile (unix commandline) or just linkage (direct compile from commandline with extra files) are the most common ways. How do you compile just 1 file?
its just a separate file to put my function.not a class
his line 12 would be in a .h file Karakuik. It is OK how he did it, but proper coding would have line 12 in add.h and main would #include "add.h". It isnt necessary, but it is the correct thing to do. Then remove line 12.

you don't have to have classes for functions. The idea of hybrid programming or functional programming has largely fallen away but sometimes a stand-alone function outside of classes is fine. They are great for pure math that has no need of an object.

for such a simple program he actually could #include the .cpp file. This is not good practice, but for 1-2 file disposable hacks, you can do it. It causes all kinds of problems if your code is even remotely complex. It would be better to understand your tools and do it properly. Its kind of like goto, its not a 'real' option, but you can do it.
Last edited on
Topic archived. No new replies allowed.