How to call function from another file in C++

In this tutorial, you will learn how to call a function from another file in C++. When we work on big projects the lines of code can become huge. What happens is that if we put all our code in one file then it becomes hard to track where a specific method was defined. To overcome this problem we define our C++ functions in another file. So you can then use them in your main C++ file.

How to define functions in another file

You can create another file called “outsidefile.h” this custom header file will contain your methods. Please keep in mind that you would have to include the necessary library or header files in either the main file or in the outside file which contains your defined method. Let’s take an example, we will try to find the absolute value of a negative number through a function which will be defined in the “outsidefile.h“. We will include the cmath library in the outside file and not in the main file. This way only the code written in the outside file will be able to use the cmath library functions. First, create the “outsidefile.h“:

//this is the outsidefile.h                                                                          

#include <cmath>

using namespace std;

void outside_function(){

cout << "Hello World!! I am an outsider :-) " << endl;

}

int absolute(int x){

        int result = abs(x);
        cout << "abs value is: " << result << endl;


return result;

}

This file contains two functions, outside_function() and absolute function. The outside_function(), when called, will print “Hello World!! I am an outsider 🙂 “. The absolute function takes an integer parameter and returns the absolute value of that integer for example -4 will become +4.

Okay, so now let’s create our main.cpp

#include <iostream>
#include "outsidefile.h"

using namespace std;

int main(){

outside_function();

int number = -4;

cout << "number before passing into the function = " << number << endl;

number = absolute(number);

cout << number << endl ;

return 0;

}

In our main.cpp we have included the “outsidefile.h” please note the syntax:

#include “outsidefile.h”

Now let’s run the main.cpp program on a Linux machine you can use the command:

g++ main.cpp && ./a.out“.

Note: you can also include other files

Output for the above code

call a function from another file in C++

Now you have successfully learned how to call a function from another file in C++.

Also read: How to dynamically allocate a 2D array in C++

Leave a Reply

Your email address will not be published. Required fields are marked *