There are a couple of ways to approach this. First is to use the keyword extern in the function declaration, this will inform the linker that the functions are declared in another file. An example of this is below:
in main:
Code:
#include <iostream>
using std::cin;
extern int getInfo(void); //function declaration
extern void displayHello(void); //function declaration
int main() {
displayHello(); //call our first function
cin.get(); //keep window open
return 0;
}
in my other file:
Code:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int getInfo(void) {
int numTimes;
cout << "How many times? ";
cin >> numTimes;
return numTimes;
}
void displayHello(void) {
int maxTime;
maxTime = getInfo();
for(int i = 0; i < maxTime; i++) {
cout << "Hello" << endl;
}
}
Now however this approach works it is better for the logical layout of your program to use header files. Basically a header file simply contains the function declarations whereas the .cpp file contains the function definitions. You would create the header file and then include that in both your source files like so:
in the header file:
Code:
#ifndef myHeader_h
#define myHeader_h
int getInfo(void); //function declaration
void displayHello(void); //function declaration
#endif
in the source file:
Code:
#include <iostream>
#include "myHeader.h"
using std::cout;
using std::cin;
using std::endl;
int getInfo(void) {
int numTimes;
cout << "How many times? ";
cin >> numTimes;
return numTimes;
}
void displayHello(void) {
int maxTime;
maxTime = getInfo();
for(int i = 0; i < maxTime; i++) {
cout << "Hello" << endl;
}
}
and finally in main:
Code:
#include <iostream>
#include "myHeader.h"
using std::cin;
int main() {
displayHello(); //call our first function
cin.get(); //keep window open
return 0;
}
the preprocessor directives #ifndef, #def, and #endif just ensure that the header file is only linked to once.