Clean up your #include statements?

后端 未结 12 1305
梦如初夏
梦如初夏 2020-12-05 13:18

How do you maintain the #include statements in your C or C++ project? It seems almost inevitable that eventually the set of include statements in a file is either insufficie

12条回答
  •  执笔经年
    2020-12-05 14:11

    I usually create one source file (main.c, for example) and one header file for that source file (main.h). In the source file, I put all the main sort of "interface" functions that I use in that file (in main, it'd be main()), and then whatever functions I get after refactoring those functions (implementation details), go below. In the header file, I declare some extern functions which are defined in other source files, but used in the source file which uses that header. Then I declare whatever structs or other data types that I use in that source file.

    Then I just compile and link them all together. It stays nice and clean. A typical include ... section, in my current project looks like this

    #include
    #include
    #include
    
    #include"interface.h"
    #include"thissourcefile.h"
    
    //function prototypes
    
    //source
    

    there's an interface header which keeps track of the data structures I use in all of the forms in the project, and then thissourcefile.h which does exactly what I just explained (declares externs, etc).

    Also, I never define anything in my headers, I only put declarations there. That way they can be included by different source files and still link successfully. Function prototypes (extern, static, or otherwise) and declarations go in the header, that way they can be used lots of times--definitions go in the source, because they only need to be in one place.

    This would obviously be different if you were creating a library, or something like that. But just for internal project linking, I find this keeps everything nice and clean. Plus, if you write a makefile, (or you just use an IDE), then compiling is really simple and efficient.

提交回复
热议问题