Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define (non-method) functions in header libraries

When writing a header library (like Boost), can one define free-floating (non-method) functions without (1) bloating the generated binary and (2) incurring "unused" warnings?

When I define a function in a header that's included by multiple source files which in turn is linked into the same binary, the linker complains about redefinitions. One way around this is to make the functions static, but this reproduces the code in each translation unit (BTW, can linkers safely dereplicate these?). Furthermore, this triggers compiler warnings about the function being unused.

I was trying to look for an example of a free-floating function in Boost, but I couldn't find one. Is the trick to contain everything in a class (or template)?

like image 622
Yang Avatar asked Nov 30 '22 06:11

Yang


1 Answers

If you really want to define the function (as opposed to declaring it), you'll need to use inline to prevent linker errors.

Otherwise, you can declare the function in the header file and provide its implementation separately in your source file.

like image 159
David Joyner Avatar answered Dec 01 '22 21:12

David Joyner