You are here: Home Help/User Support Programming (C, FORTRAN, etc.) Automated Program Compilation with 'make'

Automated Program Compilation with 'make'

make is a utility designed to automatically determine which pieces of a large program need to be recompiled, and then issue the commands to automatically recompile them. A file normally named Makefile contains rules for how program is to be compiled.

Example Makefile to Build Mixed FORTRAN, C, and C++ program

The following lines are entered into a normal text file named 'Makefile':

    .SUFFIXES: .C .f .c .o

            g77 -c $<
            g++ -c $<
            gcc -c $<

    OBJECTS=fprogram.o ffunction.o cppfunction2.o cfunction2.o

    fprogram: $(OBJECTS)
            g77 -lc -o fprogram $(OBJECTS)

The .SUFFIXES: line gives a list of file extensions that will be used in the final compilation. In this case, C, C++, and FORTRAN source code is compiled into object files.

Lines such as .f.o: show how to turn a file with a .f extension into a file with a .o extension. Similar lines show how to compile .c or .C files into object files. Make absolutely certain you prefix each command line (the gcc, g77, or similar lines) with a TAB character, not spaces. Also ensure that there is an extra blank line at the end of the Makefile.

Example Compilation with Above Makefile

Each time we run make, any source code files newer than their corresponding object files will be recompiled. Similarly, any object files newer than the final executable will cause the executable to be relinked. This first time through, none of the object files exist at all, and so all the source code files are compiled:

    mwr@ch208m:~$ make
    g77 -c fprogram.f
    g77 -c ffunction.f
    g++ -c cppfunction2.C
    gcc -c cfunction2.c
    g77 -lc -o fprogram fprogram.o ffunction.o cppfunction2.o cfunction2.o

If we make no changes to any of the files and rerun make, no recompiles should be necessary:

    mwr@ch208m:~$ make
    `fprogram' is up to date.

If we make changes to the source code in fprogram.f and cppfunction2.C, make should automatically recompile the affected object files, and relink the final executable. No other files should be recompiled:

    mwr@ch208m:~$ touch fprogram.f cppfunction2.C
    mwr@ch208m:~$ make
    g77 -c fprogram.f
    g++ -c cppfunction2.C
    g77 -lc -o fprogram fprogram.o ffunction.o cppfunction2.o cfunction2.o

Additional Information

For more information, see this make tutorial from the University of Hawaii.

Filed under: , , ,