0
votes

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
What exactly is in c.hpp? Just the prototype, or also the implementation? By your edit I am assuming the full implementation. - indiv
Only put a declaration of the function in the header. Put the definition of the function into c.pp. - Jerry Coffin
The general rules is to put prototypes and class/struct definitions in your header files and put the implementation in a c/cpp file. - Retired Ninja
@JerryCoffin But I often see implementations of setter/getter functions for classes in the header. Why isn't this a problem? - dfg
Inline functions (either explicitly marked as inline, or defined inside a class definition) have slightly different rules, that allow multiple definitions as long as they're all identical. - Jerry Coffin

2 Answers

3
votes

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.

1
votes

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.