Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Headers Vs. Static Libraries

I am planning to do some utility code for using in other projects, but I am doubting between making it a mostly-headers code, a static library with headers just exposing the interface or something in between. Most of the code will be simple functions that wrap other standard functions but there will be also some bigger functions.

I think I mostly understand the differences between the header approach and the static library approach:

For the headers:

  • All the code will be in headers
  • Better oportunities for the compiler to inline code
  • Every function will have to be compiled every time it is used

For the static library:

  • Mixed code between the library and the headers
  • Worse oportunities for the compiler to inline code
  • Compile once and forget

I have been looking at some code and I have seen both approaches, but I don't know which will be better. Any thoughts?

like image 932
Noxbru Avatar asked Mar 26 '26 22:03

Noxbru


2 Answers

It's often possible to write your headers such that macros can be used to conditionally include the entire library (for compiling in one unit) or only declarations (for linking against static/shared objects or compiling in separate units) at the user's option. Using a macro like this has the added benefit that, assuming separate library sources and/or objects exist, the choice can be deferred to just before compilation and controlled by a build tool. The obvious drawback to this is the utter mess it can make of your code and all the complexity and cognitive strain that comes with using macros for conditional compilation.

Whether any given option (header/header+source/static-lib/shared-lib/etc.) is appropriate, or if the above option is useful or even possible, depends on what exactly you're doing.

like image 105
acwaters Avatar answered Mar 28 '26 14:03

acwaters


I prefer to write it as a static library rather than using headers.

  • If you use headers it'll be inlined in the code which makes the code size to be large (if you're using an embedded system this is a disadvantage)
  • More compilation time will be required to compile the whole inlined function
  • But inlining saves times for context swiching while calling a function but this will be only in the range of a few microseconds(consider the penalty of code size also while using header method)
  • Implementing some functions are difficult by header method and more error prone refer: https://gcc.gnu.org/onlinedocs/cpp/Macro-Pitfalls.html
  • All the standard libraries made by the component/development board manufactures are static library method

;

like image 33
Sorcrer Avatar answered Mar 28 '26 12:03

Sorcrer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!