Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call functions from one .cpp file in another .cpp file?

Tags:

c++

I tried looking this up and got mixed results using header files and such.

Basically I have multiple .cpp files with all my functions I made for use with binary trees, BST, linked lists, etc.

Instead of having to copy and paste functions as I need them, I want to just be able to do a:

#include <myBSTFunctions.h>

And be able to call and use my own functions.

What are the steps to accomplish this? Make a header file with all the function prototypes I used?

And where should I place the cpp and header file with all the actually functions?

Is there a way I can call the directory of the functions file directly?

I.e., I'm more thinking of having it in the same folder with the main source cpp file to share with some of my colleagues.

How can I accomplish this?

On Windows and the MinGW compiler.

like image 910
Emrit Avatar asked Jul 23 '18 22:07

Emrit


1 Answers

That is quite simple, as JMAA said you should do some research to understand these concepts, but being practical, this is what you would do:

You'll define an functionsExample.cpp where you have to define all your functions and also an functionsExample.h where you'll declare your functions.

You'll have this as the functionsExample.cpp:

#include <iostream>
int example(int x, int y)
{
    return x + y;
}

Ans this as functionsExample.h:

#ifndef FUNCTIONSEXAMPLE_H
#define FUNCTIONSEXAMPLE_H

int example(int x, int y);

#endif 

Then in the cpp you want to run the example function, simply add:

#include "functionsExample.h"

But as I said, you should do some research about header guards, preprocessor directives and files organization to have a deeper knowledge about this. Some links I would recommend:

Header Files

Preprocessor Directives

like image 139
Caio Gomes Avatar answered Sep 23 '22 20:09

Caio Gomes