I had a single source file which had all the class definitions and functions.
For better organization, I moved the class declarations(.h) and implementations(.cpp) into separate files.
But when I compiled them, it resulted in a slower executable than the one I get from single source executable. Its around 20-30 seconds slower for the same input. I dint change any code.
Why is this happening? And how can I make it faster again?
Update: The single source executable completes in 40 seconds whereas the multiple source executable takes 60. And I’m referring to runtime and not compilation.
I think, your program runs faster when compiled as a single file because in this case compiler has more information, needed to optimize the code. For example, it can automatically inline some functions, which is not possible in case of separate compilation.
To make it faster again, you can try to enable link-time optimizer (or whole program optimizer) with this option:
-flto.If
-fltooption is not available (and it is available only starting with gcc 4.6) or if you don’t want to use it for some reason, you have at least 2 options:for better organization, you can create a single source file (likeall.cxx) and#includeall source files (all other*.cxxfiles) to this file. Then you need to build only thisall.cxx, and all compiler optimizations are available again. Or, if you split it also to make compilation incremental, you may prepare 2 build options: incremental build and unity build. First one builds all separate sources, second one – onlyall.cxx. See more information on this here.