Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function from another header file in C++?

Tags:

c++

function

I have the following 3 files (1 *.cpp and 2 *.hpp) :

the main program file:

// test.cpp

#include<iostream>
#include"first_func.hpp"
#include"sec_func.hpp"

int main()
{
    double x;
    x = 2.3;
    std::cout << sec_func(x) << std::endl;
}

- the first_func.hpp header:

// first_func.hpp

...

double  first_func(double x, y, x)
{

    return x + y + x;
}

- the sec_func.hpp header:

// sec_func.hpp

...

double sec_func(double x)
{
        double a, b, c;
        a = 3.4;
        b = 3.3;
        c = 2.5;

        return first_func(a,b,c) + x;
}

How do I properly call first_func from within the sec_func.hpp file?

like image 785
tagoma Avatar asked Dec 07 '22 13:12

tagoma


1 Answers

For most functions, the implementation should reside in a compilation unit, that is a file that is going to be compiled by itself and compiled once.

Headers are not to be compiled by themselves*, instead they are included by multiple compilation units.

That's why your function definitions should reside in compilation units (like .cpp), not in headers. Headers should contain only the declarations (i.e. without the body), just enough so that other compilation units would know how to call them.


For completeness, the functions that generally need to be defined in headers (as an exception) are:

  • inline functions
  • template functions** (classes too)

Footnotes:

* headers can actually be pre-compiled, but that's a solution for speeding up compilation and it doesn't alter their purpose; don't get confused by that.
** you can put template function definitions outside of the headers if you use explicit template instantiation, but that's a rare case; the point is that every compilation unit that wants to instantiate a template (apply arguments to it) needs to have its complete definition, that's why template function definitions go into headers too.

like image 53
Kos Avatar answered Dec 09 '22 14:12

Kos