#include in .h or .c / .cpp?

后端 未结 4 759
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 10:29

When coding in either C or C++, where should I have the #include\'s?

callback.h:

#ifndef _CALLBACK_H_
#define _CALLBACK_H_

#include <         


        
相关标签:
4条回答
  • 2020-12-12 10:57

    Put as many includes in your cpp as possible and only the ones that are needed by the hpp file in the hpp. I believe this will help to speed up compilation, as hpp files will be cross-referenced less.

    Also consider using forward declarations in your hpp file to further reduce the include dependency chain.

    0 讨论(0)
  • 2020-12-12 10:58

    Put as much as you can in the .c and as little as possible in the .h. The includes in the .c are only included when that one file is compiled, but the includes for the .h have to be included by every file that uses it.

    0 讨论(0)
  • 2020-12-12 11:13

    The only time you should include a header within another .h file is if you need to access a type definition in that header; for example:

    #ifndef MY_HEADER_H
    #define MY_HEADER_H
    
    #include <stdio.h>
    
    void doStuffWith(FILE *f); // need the definition of FILE from stdio.h
    
    #endif
    

    If header A depends on header B such as the example above, then header A should include header B directly. Do NOT try to order your includes in the .c file to satisfy dependencies (that is, including header B before header A); that is a big ol' pile of heartburn waiting to happen. I mean it. I've been in that movie several times, and it always ended with Tokyo in flames.

    Yes, this can result in files being included multiple times, but if they have proper include guards set up to protect against multiple declaration/definition errors, then a few extra seconds of build time isn't worth worrying about. Trying to manage dependencies manually is a pain in the ass.

    Of course, you shouldn't be including files where you don't need to.

    0 讨论(0)
  • 2020-12-12 11:19

    If I #include <callback.h>, I don't want to have to #include lots of other header files to get my code to compile. In callback.h you should include everything needed to compile against it. But nothing more.

    Consider whether using forward declarations in your header file (such as class GtkButton;) will suffice, allowing you to reduce the number of #include directives in the header (and, in turn, my compilation time and complexity).

    0 讨论(0)
提交回复
热议问题