2.3 Compiling multiple source files
A program can be split up into multiple files. This makes it easier to
edit and understand, especially in the case of large programs--it also
allows the individual parts to be compiled independently.
In the following example we will split up the program Hello World
into three files: 'main.c', 'hello_fn.c' and the header file
'hello.h'. Here is the main program 'main.c':
#include "hello.h"
int
main (void)
{
hello ("world");
return 0;
}
The original call to the printf
system function in the previous
program 'hello.c' has been replaced by a call to a new external
function hello
, which we will define in a separate file
'hello_fn.c'.
The main program also includes the header file 'hello.h' which will
contain the declaration of the function hello
. The declaration
is used to ensure that the types of the arguments and return value match
up correctly between the function call and the function definition. We
no longer need to include the system header file 'stdio.h' in
'main.c' to declare the function printf
, since the file
'main.c' does not call printf
directly.
The declaration in 'hello.h' is a single line specifying the
prototype of the function hello
:
void hello (const char * name);
The definition of the function hello
itself is contained in the
file 'hello_fn.c':
#include <stdio.h>
#include "hello.h"
void
hello (const char * name)
{
printf ("Hello, %s!\n", name);
}
This function prints the message "Hello,
name!
"
using its argument as the value of name.
Incidentally, the difference between the two forms of the include
statement #include "FILE.h"
and #include
<FILE.h>
is that the former searches for 'FILE.h' in
the current directory before looking in the system header file
directories. The include statement #include <FILE.h>
searches the system header files, but does not look in the current
directory by default.
To compile these source files with gcc
, use the following
command:
$ gcc -Wall main.c hello_fn.c -o newhello
In this case, we use the -o
option to specify a different output
file for the executable, 'newhello'. Note that the header file
'hello.h' is not specified in the list of files on the command
line. The directive #include "hello.h"
in the source files
instructs the compiler to include it automatically at the appropriate
points.
To run the program, type the path name of the executable:
$ ./newhello
Hello, world!
All the parts of the program have been combined into a single executable
file, which produces the same result as the executable created from the
single source file used earlier.