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

后端 未结 10 1193
悲&欢浪女
悲&欢浪女 2020-12-22 18:46

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 h

10条回答
  •  执念已碎
    2020-12-22 19:20

    On top of what everybody else added and what you're already doing (parallelized build, compiler options, etc), consider hiding templates in implementation classes, accessed through interfaces. That means that instead of having a class like:

    // ClsWithNoTemplates.h file, included everywhere
    
    class ClsWithTemplates
    {
        ComplicatedTemplate member;
        // ...
    
    public:
        void FunctionUsingYourMember();
    };
    

    you should have:

    // ClsWithNoTemplates.h file:
    
    class ClsWithTemplatesImplementation; // forward declaration
      // definition included in the ClsWithNoTemplates.cpp file
      // this class will have a ComplicatedTemplate member, but it is only 
      // included in your ClsWithNoTemplates definition file (that is only included once)
    
    
    class ClsWithNoTemplates
    {
         ClsWithTemplatesImplementation * impl; // no templates mentioned anywhere here
    public:
        void FunctionUsingYourMember(); // call impl->FunctionUsingYourMember() internally
    };
    

    This changes your OOP design a bit, but it's for the good: including the definition of 'ClsWithNoTemplates' is now fast and you only (pre)compile the definition of 'ClsWithNoTemplates' once.

    Aditionally, if you change the implementation code, any code that included ClsWithNoTemplates.h will probably not need to be redefined.

    This change should dramatically increase your partial compilation time, and it will also help in the case where your ClsWithNoTemplates is a public interface exported from a library file: since the file is not changed when you only change the implementation, your dependent client code doesn't need to be recompiled at all.

提交回复
热议问题