Rely on compiler to remove unused code or #ifdef out

ccompileroptimization

I am working on a USB stack in C. This stack will be open source and used in various different projects.

Various configuration options are available, which enable or disable large chunks of code and constant data structures. As this is an embedded project it is important to minimize the footprint of the stack, and one of the benefits of disabling unused features is a reduction in flash and RAM use.

There are two ways to remove unused code from the build process output. Using #ifdef preprocessor directives causes the compiler to not even consider the unusued code. The main disadvantages are polluting the code with lots of #ifdefs and the potential to break disabled code and not get a compiler warning/error.

The other option is to include the code but allow the linker to eventually remove it. GCC is very good at this, and the resulting output is the same size as if it was removed with #ifdef. The down side to this is that it requires at least a minimum level of optimization to be enabled (-O1, functions in sections and unused section removal) and this behaviour isn't guaranteed on other compilers, or even other versions of GCC.

What is the best practice here and why? What are the advantages and disadvantages I have not considered?

Best Answer

Go for preprocessor directives. They shouldn't pollute too much the code (if they do, you can probably refactor those sections and extract them to a separate, possibly inlined, function, increasing its maintainability).

In my opinion, the most important point is that you can't know whether that section of code will actually be used or not. Today's modern IDEs can highlight or dim those sections depending on the configuration you're building to, when inside an #if...#endif block. This makes that code more maintainable and easy to identify. Relying solely on the compiler/optimizer will make that clear just to itself, with no practical advantage in terms of efficiency, performance, or program size.