Search code examples
cgccltotranslation-unit

Splitting code into files and O flags


When writing programs with code that can be executed in parallel in C, we definitely use the O flags to optimize the code.

gcc -Olevel [options] [source files] [object files] [-o output file]

In large projects, we usually split the code into several files. My question, for which I've found no answer, is this:

Does the program's performance drop at all, due to the fact that we split the code into files and the O flags don't have enough information to optimize any further? Is there such a possibility?


Solution

  • When you break code into separate files, it could potentially split it into more than one translation unit, which the compiler generally can't optimize across.

    Take for example a constant defined in one translation unit but referenced in a number of others. All of the calculations that reference the constant have to be performed at run-time since the constant can't be folded into them at compile time.

    Link-time optimization (-flto) is one way around the limitation.