Including one C source file in another?

srujan picture srujan · Oct 24, 2008 · Viewed 162.5k times · Source

Is it OK (or even recommended/good practice) to #include a .c file in another .c file?

Answer

forgot_my_OpenId picture forgot_my_OpenId · Jul 10, 2009

Used properly, this can be a useful technique.

Say you have a complex, performance critical subsystem with a fairly small public interface and a lot of non-reusable implementation code. The code runs to several thousand lines, a hundred or so private functions and quite a bit of private data. If you work with non-trivial embedded systems, you probably deal with this situation frequently enough.

Your solution will probably be layered, modular and decoupled and these aspects can be usefully represented and reinforced by coding different parts of the subsystem in different files.

With C, you can lose a lot by doing this. Almost all toolchains provide decent optimisation for a single compilation unit, but are very pessimistic about anything declared extern.

If you put everything into one C source module, you get -

  • Performance & code size improvements - function calls will be inlined in many cases. Even without inlining, the compiler has opportunities to produce more efficient code.

  • Link level data & function hiding.

  • Avoidance of namespace pollution and its corollary - you can use less unwieldy names.

  • Faster compilation & linkage.

But you also get an unholy mess when it comes to editing this file and you lose the implied modularity. This can be overcome by splitting the source into several files and including these to produce a single compilation unit.

You need to impose some conventions to manage this properly though. These will depend on your toolchain to some extent, but some general pointers are -

  • Put the public interface in a separate header file - you should be doing this anyway.

  • Have one main .c file that includes all the subsidiary .c files. This could also include the code for the public interface.

  • Use compiler guards to ensure that private headers and source modules are not included by external compilation units.

  • All private data & functions should be declared static.

  • Maintain the conceptual distinction between .c and .h files. This leverages existing conventions. The difference is that you will have a lot of static declarations in your headers.

  • If your toolchain doesn't impose any reason not to, name the private implementation files as .c and .h. If you use include guards, these will produce no code and introduce no new names (you may end up with some empty segments during linkage). The huge advantage is that other tools (e.g. IDEs) will treat these files appropriately.