Functions in a header-only library should be declared as inline
to prevent multiple definitions in the different translation units. That is, for example, I wrote a header-only library mylib.hpp
:
void do_something(int) {}
And I used this header in two different cpp file:
// a.cpp
# include "mylib.hpp"
void func1() {do_something(1);}
// b.cpp
# include "mylib.hpp"
void func2() {do_something(2);}
Build them with g++ -o main a.cpp b.cpp
, GCC will complain with "multiple definition of do_something(int)
". To prevent this, define the function like static void do_something(int) {}
to make it have a copy in each translation unit (that is, have two copies in the last output), or define the function like inline void do_something(int) {}
to have exactly a single copy in the last output, which is what we want.
However, if I want to force do_something
not to be inlined by the compiler (for example, I want to use backtrace library to dynamically find out which function called do_something
), I should write it like:
[[gnu::noinline]] inline void do_something(int) {}
However, GCC complains:
Warning: inline declaration of ‘do_something(int)’ follows declaration with attribute ‘noinline’ [-Wattributes]
So, what is the proper way to do such things?