How expensive it is for the compiler to process an include-guarded header?

后端 未结 3 1067
后悔当初
后悔当初 2021-01-16 23:01

To speed up the compilation of a large source file does it make more sense to prune back the sheer number of headers used in a translation unit, or does the cost of compilin

3条回答
  •  日久生厌
    2021-01-16 23:54

    I read an FAQ about this the other day... first off, write the correct headers, i.e. include all headers that you use and don't depend on undocumented dependencies (which may and will change).

    Second, compilers usually recognize include guards these days, so they're fairly efficient. However, you still need to open a lot of files, which may become a burden in large projects. One suggestion was to do this:

    Header file:

    // file.hpp
    
    #ifndef H_FILE
    #define H_FILE
    
    /* ... */
    
    #endif
    

    Now to use the header in your source file, add an extra #ifndef:

    // source.cpp
    
    #ifndef H_FILE
    #  include 
    #endif
    

    It'll be noisier in the source file, and you require predictable include guard names, but you could potentially avoid a lot of include-directives like that.

提交回复
热议问题