Writing and Compiling C Program in Linux Part 3: Using Makefile

Compiling C Program using Make

  • Using the example in Part 2, instead of compiling line by line, we can create a make file that will follow certain compiling instructions.
  • The format for the make file is:

target: dependencies

command

  • The file is usually called Makefile
  • The Makefile of previous tvm program will be as follows:
#Creating object
tvm2: tvm2.o finlib.o
gcc tvm2.o finlib.o -lm -o tvm2
tvm2.o: tvm2.c fin.h
gcc -c tvm2.c
finlib.o: finfn.c fin.h
gcc -c finfn.c -o finlib.o
clean:
rm -f tvm2 tvm2.o finlib.o
  • This is the more explicit way to instruct the make program how to compile line by line.
  • Please note that the final program must come first before compilation of object. It is a drill down approach.
  • After the make file is written, you can package all the program and Makefile together.
  • To compile the program just type #make
  • To remove the compiled program and object type #make clean
  • However, we need not be so explicit because make program know how to compile programs.
  • See the example below:
CFLAGS=-Wall
LDFLAGS=-lm
#Creating object
tvm: tvm.o finfn.o fin.h
clean:
rm -f tvm tvm.o finfn.o
  • CFLAGS refers to compile flags
  • LDFLAGS refers to linking flags
  • By indicating our target program and the dependencies, the make program will compile the program and link them appropriately using the flags indicated.
  • Since the custom library need not compile every time, we can include the main C program and the object file of the library.
  • The Makefile will be slightly different, as follows:
CFLAGS=-Wall
LDFLAGS=-lm
#Creating object
tvm: tvm.o finlib.o fin.h
clean:
rm -f tvm tvm.o
  • We don’t supply finfn.c but we supply a precompiled object file finlib.o.
Advertisements

One Response to Writing and Compiling C Program in Linux Part 3: Using Makefile

  1. unusual says:

    rock on! This is a great blog and I couldn’t have said it better!

%d bloggers like this: