Should I use #include in headers?

后端 未结 9 1187
甜味超标
甜味超标 2020-11-22 04:55

Is it necessary to #include some file, if inside a header (*.h), types defined in this file are used?

For instance, if I use GLib and wish to use the

9条回答
  •  悲哀的现实
    2020-11-22 05:13

    Yes it is necessary or the compiler will complain when it tries to compile code that it is not "aware" of. Think of #include's are a hint/nudge/elbow to the compiler to tell it to pick up the declarations, structures etc in order for a successful compile. The #ifdef/#endif header trick as pointed out by jldupont, is to speed up compilation of code.

    It is used in instances where you have a C++ compiler and compiling plain C code as shown here Here is an example of the trick:

    #ifndef __MY_HEADER_H__
    #define __MY_HEADER_H__
    
    #ifdef __cplusplus
    extern "C" {
    #endif
    
    
    /* C code here such as structures, declarations etc. */
    
    #ifdef __cplusplus
    }
    #endif
    
    #endif /* __MY_HEADER_H__ */
    

    Now, if this was included multiple times, the compiler will only include it once since the symbol __MY_HEADER_H__ is defined once, which speeds up compilation times. Notice the symbol cplusplus in the above example, that is the normal standard way of coping with C++ compiling if you have a C code lying around.

    I have included the above to show this (despite not really relevant to the poster's original question). Hope this helps, Best regards, Tom.

    PS: Sorry for letting anyone downvote this as I thought it would be useful tidbit for newcomers to C/C++. Leave a comment/criticisms etc as they are most welcome.

提交回复
热议问题