Multiple files need a function?

90 views Asked by At

Say I have two files a.cpp and b.cpp and they both use a function in c.hpp. If I #include "c.hpp" in both a.cpp and b.cpp I would get an error during linking saying the symbol has been defined twice (since header guards don't prevent inclusion across multiple translation units)

So how do I give both .cpp files access to the function in c.hpp without getting an error during linking?

2

There are 2 answers

2
Jay Miller On BEST ANSWER

For a long function you would want to give the function it's own translation unit, moving the implementation to it's own CPP and only keeping the declaration in the header.

If the function is short you can add the inline keyword:

inline void myfunction() ...

This allows the compiler to inline the function in each translation unit, avoiding the multiple definintions.

0
Ips On

In most cases the header file should contain just the declaration of the function, i.e. the function header. The function definition (the body) should be contained in a separate .cpp file. So in your case, it should look like this:

c.hpp:

int my_function(int x, int y);

c.cpp:

#include "c.hpp"

int my_function(int x, int y)
{
    return x + y;
}

and add #include "c.hpp" to any other file where you wish to use my_function. All .cpp files will be compiled separately and linker will handle the rest.