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

后端 未结 4 772
隐瞒了意图╮
隐瞒了意图╮ 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 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 
    
    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.

提交回复
热议问题