The exact procedure would depend on the compiler, though will not vary widely. Since we work extensively on Linux, we will show you how to do so using the GCC compiler in Linux:
The simplest way of combining multiple C programs to create a single executable is:
$gcc 1.c 2.c 3.c
The files 1.c
, 2.c
and 3.c
will be individually compiled, and the generated object codes will be linked together and with the standard library to create an executable called a.out. Note that on some systems, the command to compile is cc
instead of gcc
, but without any other difference.
The long cut for doing the same is:
$gcc -c 1.c $gcc -c 2.c $gcc -c 3.c $gcc 1.o 2.o 3.o
In this case, we individually compile (-c
stands for ‘only compile’) each of the 3 files, with the object codes being written on to corresponding .o
files. We then ask gcc
to link these object codes together along with the standard library. An advantage of this long cut is that if we change a few files, we need to only recompile those files we had changed and link the object codes together, without having to unecessarily recompile all files. Of course, an even better technique is to use makefiles, which hopefully will be covered by a separate article in this blog later.
Many IDE allow the user to create a “project” comprising of C files, and a “build” option to compile all changed files and link the object codes together, giving rise to a single executable.
Related Questions:
Q: What are the steps in the compilation process?
Q: What are the basic options of gcc that I need to know?
Q: What are makefiles? How can they help?
Q: What are the free IDE available for C?