Search code examples
cgccstaticlinkerheader-files

Can gcc's linker fold multiple instantiations of a static function in a C header into a single instance?


The embedded C code I'm writing has numerous (i.e. >100) small static accessor functions defined in headers, but I'd be uncomfortable moving them out of the headers because the overall code clarity would suffer. :-(

Is gcc's linker smart enough to fold multiple instantiations of header-defined static functions into single instances within the final binary? More generally, do the C standards define linker behaviour for multiple identical instantiations of static functions defined in headers? Thanks!

To be precise: if static functions defined in headers refer to static data, then I can see that the linker would be unable to fold multiple instantiations together, because each function instance would refer to a different instance of that static data. However, where static functions defined in a header don't refer to static data, the compiled instantiations would be basically identical (bar the inevitable compiler static-naming kruft wrapped around them). Which is why I ask if gcc's linker is "smart" enough. :-)


Solution

  • Gold and lld linkers perform identical code folding (so with some luck all local definitions will be coalesced) but GNU ld does not so the best approach would be to replace static with inline (duplicate inline definitions are guaranteed to be merged).