I have some small utility functions (< 20 lines of code per function) that I am currently putting in a utils.h
file with the keyword inline
in front of them so I don't run into multiple definition
linking errors. This is what I have always done for small functions.
I am wondering what the advantages and disadvantages are to:
Using my method
Putting the function declarations in
utils.h
and definitions inutils.cpp
CodePudding user response:
Disadvantage of inline:
- If the header is included into many TU, the build time is slowed due to building of the function for each TU (this may be diminished if pre-built header is an option).
- When you make any change to the implementation, then all TU that include the header must be re-compiled. This is especially bad if the implementation changes often (bugs, new features, etc.) and when the header is used in many TU.
- If the implementation depends on any definition / declarations, then those dependencies transfer to all TU that include the header. This increases the time to build those TU and spreads the rebuilding caused by changes to the dependencies too. If the dependencies are system specific, then this complicates compatibility between systems.
Advantages of inline:
- If you reduce the number of TU; then build time from scratch improves.
- It allows inline expansion to the TU that include it (but that is also allowed by using link time optimisation).
CodePudding user response:
For header vs. source there is a HUGE speed difference for small functions here. Basically anything that the compiler would always inline is a good candidate to be in the header.
The potential gains inlineing gives you come at the cost of compile time. It can also be nice for debugging purposes to have an actual function that gets called in the binary where you can set a breakpoint.
Generally if the function it not called often then put it in the source file, it's just neater and nobody cares. Especially something with 20 lines excluding boiler plate. That's not really small. Only put stuff in the header that is time sensitive.
And do check out if your compiler can do LTO (link time optimization). Because with that you can have functions in the source and still get them inlined when you use LTO. But while developing you can compile without LTO and get quick builds (and slower binaries). So with LTO you can have your cake and eat it too.
Overall I would draw the line for functions in headers far lower than 20 lines. If your function only has a return statement then put it in the header, otherwise the source, and use LTO. That's my rule-of-thumb.