Best practice for including from include files

后端 未结 6 1180
谎友^
谎友^ 2021-01-21 02:05

I was wondering if there is some pro and contra having include statements directly in the include files as opposed to have them in the source file.

Personally I like to

6条回答
  •  既然无缘
    2021-01-21 02:30

    On the other hand, if I have the includes in the include files compile time might get bigger, because even with the include guards

    If your compiler doesn't remember which files have include guards and avoid re-opening and re-tokenising the file then get a better compiler. Most modern compilers have been doing this for many years, so there's no cost to including the same file multiple times (as long as it has include guards). See e.g. http://gcc.gnu.org/onlinedocs/cpp/Once_002dOnly-Headers.html

    Headers should be self-sufficient and include/declare what they need. Expecting users of your header to include its dependencies is bad practice and a great way to make users hate you.

    If my_needed_file.h is needed before sample.h (because sample.h requires declarations/definitions from it) then it should be included in sample.h, no question. If it's not needed in sample.h and only needed in sample.c then only include it there, and my preference is to include it after sample.h, that way if sample.h is missing any headers it needs then you'll know about it sooner:

    // sample.c
    #include "sample.h"
    #include "my_needed_file.h"
    #include ...
    #include 
    // ...
    

    If you use this #include order then it forces you to make sample.h self-sufficient, which ensures you don't cause problems and annoyances for other users of the header.

提交回复
热议问题