multiple files

hello all!
I'm new to C++ and I'm trying to make a program that has multiple files

in the main.cpp I did
1
2
3
4
5
6
7
#include <iostream>	 
int main()
{
		    using namespace std;
		    cout << "The sum of 3 and 4 is: " << add(3, 4) << endl;
		    return 0;
		}

and in the second file (add.cpp) I did
1
2
3
4
int add(int x, int y)
{
		    return x + y;
		}
however, in main.cpp on line 5 it gave me a error saying add was not declared
please help! Thanks in advance!
When the compiler gets to line 5, it sees that you want to use a function called add. To use such a function, the compiler must know what the input parameters to the function are, and what the returned parameter is.

The compiler knows this information in one of two ways. Either the function is declared already, like this:

int add(int x, int y);

or the entire definition has already been seen by the compiler. Remember that every file you compile is compiled separately, so having the definition in one file does not mean the compiler automatically knows about that definition when compiling the other files.

I suggest you create a header file, like follows:

add.h
int(add int x, int y);

and add to the top of your main.cpp
#include "add.h"

By doing this, you will in effect be inserting the line
int(add int x, int y);
at the top of your main.cpp and in doing so the compiler will know the input and output types for the function.



Last edited on
Topic archived. No new replies allowed.