C++ – How to speed up g++ compile time (when using a lot of templates)

ccompilationg++templates

This question is perhaps somehow odd, but how can I speed up g++ compile time? My C++ code heavily uses boost and templates. I already moved as much as possible out of the headers files and use the -j option, but still it takes quite a while to compile (and link).

Are there any tools out there which analyse my code and point out bottle-necks for the compiler? Or can one somehow profile the compiler running on my code? This would be really nice, because sometimes I have the impression, that I spent too much time staring at the compiler console log …

Best Answer

What has been most useful for me:

  • Build on a RAM filesystem. This is trivial on Linux. You may want to keep a copy of common header files (precompiled or the actual .h files) on the RAM filesystem as well.
  • Precompiled headers. I have one per (major) library (e.g. Boost, Qt, stdlib).
  • Declare instead of include classes where possible. This reduces dependencies, thus reduces the number of files which need to be recompiled when you change a header file.
  • Parallelize make. This usually helps on a case-by-case basis, but I have -j3 globally for make. Make sure your dependency graphs are correct in your Makefile, though, or you may have problems.
  • Use -O0 if you're not testing execution speed or code size (and your computer is fast enough for you not to care much about the (probably small) performance hit).
  • Compile each time you save. Some people don't like this, but it allows you to see errors early and can be done in the background, reducing the time you have to wait when you're done writing and ready to test.