Header Files and
Multiple File Compilation


Java Compile and Execute:
C Compile and Execute:

Consider executing the command:

This is a two-step process: first the compiler creates the object file myhello.o and then the linker creates the executable, myhello. Check this by using an ls command to see that the object file is present. You can do these two steps explicitly as follows:

The first line creates myhello.o and the second line creates myhello from myhello.o.

If you have several functions, you can put some of them in another file and compile them separately.


Extended Example: Calculating Primes (The Sieve of Eratosthenes) In CS 1713 you may have done a problem of calculating primes using a sieve. The idea is as follows for calculating the primes less than 2000:

Here are the prototypes of some functions we might use for this program:

Below, we will put the function definitions into a file named sieve.c and the prototypes into a file named sieve.h. Note that the first two functions will be called by the function makeSieve and do not need to be accessible outside the file. (In Java, we would declare these "helper" functions private.)

In C, we declaring such functions static, meaning that the functions are not accessible outside the file, and their names do not appear in the sieve.h file. (This use of the word static is confusing and counter-intuitive.)

Then create a separate file called sievemain.c which contains the main program:

Here is the sieve.h file:

Here is the file with the other external functions, the sieve.c file. Notice that it also includes the header file sieve.h to insure that the two source files are compatible.

Finally, here is a makefile for this program:

The output of this program is the following:


The sieve program in C and Java: For much more about this program, along with a side-by-side C and Java comparison, see Sieve in C and Java.

For a great poem about sieves, see The Jumblies, by Edgar Lear.


Copyright © 2011, Neal R. Wagner. Permission is granted to access, download, share, and distribute, as long as this notice remains.