I'm learning C++, and I'm working on a project. In this project, I need to call functions inside functions to allow navigation on a square grid. I have my functions defined above my int main(), then a short user input that calls the first function to get it started. However, when compiling, it won't let me compile a function that calls a function that hasn't been defined yet. I was wondering how I could fix this, and if it was to put all my functions inside a header, and then include the header in the main file that calls the first function.
Headers should only contain function prototypes:
MyHeader.h
1 2 3 4
#pragma once //so multiple includes of the same header will be ignored
int myFunction1(); //declares myFunction1, but leaves it undefined
int myFunction2(); //dito
Then define them in a sepereate source file (or in multiple separate source files if you feel like it)
MySource.cpp
1 2 3 4 5 6 7 8 9 10
#include "MyHeader.h"
int myFunction1() {
if(std::rand()%2) return 1;
return myFunction2();
}
int myFunction2() {
if(std::rand()%2) return 2;
return myFunction1();
}
Then it depends on the compiler you're using, but if you're compiling from the command line it will look something like this (example with gcc, other compilers will obviously look a bit different, but with mostly the same process).
1 2 3
gcc -c MySource.cpp //compile MySource to MySource.o
gcc -c main.cpp //compile main to main.o
gcc MySource.o main.o -o test //link MySource.o and main.o to test
In and IDE, this will be done automatically just by adding the source file to the project and then hitting compile. Is that clear?
Place the definition of the called internally function before the calling function. Or you can only declare the called function before the calling function and set its definition later. For example
1 2 3 4 5 6 7 8 9 10 11
int f1( int );
int f2( int x )
{
return ( f1( x ) );
}
int f1( int x )
{
return ( x );
}