Can I write C++ code without headers (repetitive function declarations)?

前端 未结 24 931
半阙折子戏
半阙折子戏 2020-11-28 07:55

Is there any way to not have to write function declarations twice (headers) and still retain the same scalability in compiling, clarity in debugging, and flexibility in desi

24条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 08:36

    It's completely possible to develop without header files. One can include a source file directly:

    #include "MyModule.c"
    

    The major issue with this is one of circular dependencies (ie: in C you must declare a function before calling it). This is not an issue if you design your code completely top-down, but it can take some time to wrap ones head around this sort of design pattern if you're not used to it.

    If you absolutely must have circular dependencies, one may want to consider creating a file specifically for declarations and including it before everything else. This is a little inconvenient, but still less pollution than having a header for every C file.

    I am currently developing using this method for one of my major projects. Here is a breakdown of advantages I've experienced:

    • Much less file pollution in your source tree.
    • Faster build times. (Only one object file is produced by the compiler, main.o)
    • Simpler make files. (Only one object file is produced by the compiler, main.o)
    • No need to "make clean". Every build is "clean".
    • Less boiler plate code. Less code = less potential bugs.

    I've discovered that Gish (a game by Cryptic Sea, Edmund McMillen) used a variation on this technique inside its own source code.

提交回复
热议问题