Splitting a Program into Multiple Files
Learn about a general practice to divide code into different categories or files.
We'll cover the following...
The programs we have seen so far have all been stored in a single source file. As our programs become larger and as we start to deal with other people’s code (e.g. other C libraries), we have to deal with code that resides in multiple files. Indeed, we may build up our own library of C functions and data structures that can be reused in our own scientific programming and data analysis.
Here, we’ll see how to place C functions and data structures in their own file(s) and how to incorporate them into a new program.
Reusing code
We saw in the section on functions that one way of including custom-written functions in our C code is to simply place them in our main source file—either above the declaration of the main
function or below it with the function prototype appearing above the main
function.
A better way to reuse functions that we commonly incorporate into our C programs is to place them in a separate file, and to include a directive above main
to include that file.
When compiled, it’s just like the code getting copy pasted above the main
function, but for the purpose of editing and writing our code, this allows us to keep things in separate files. It also means that if we ever decide to change one of those reusable functions (for example, if we find and fix an error), then we only have to change it in one place and don’t have to go searching through all of our programs and change each one.
Header files
A common convention in C programs is to write a header file (with .h suffix) for each source file (.c suffix) that we ...