How to reduce output size of template-heavy C++ code?

--ffunction-sections will put each function in its own segment. Not useful in its own right, but the linker can remove unused sections with --gc-sections. Now without --ffunction-sections this would only work if an entire source file was unused, i.e. with an insane granularity.

Obviously you need the visibility attribute mentioned by Matthieu, else all functions in the library are "used" by virtue of being visible.


Moving the spirit aware code to .cpp files is a good first step, it might be incomplete though as you mention having spirit grammar in header files.

  1. Make sure than none of the grammar / rules are ever exported outside the library. If you have the typical include/src directories, then move those files (even if headers) within the src directory.

  2. Mark all those symbols as internal to the library. They should not be accessible from outside the library at all. There are specific pragmas/attributes depending on your compiler, on gcc lookup the visibility attribute: __attribute__ ((visibility ("internal"))). This helps the compiler optimizing them accordingly, notably a compiler may emit the code of a function even if it inlines it at a given call site, just in case this function address is taken. With internal visibility however, since it knows the code will not leave the object, it may elide the function.

  3. I seem to remember a flag to fuse identical function bodies but cannot seem to find again...