Wednesday, December 1, 2010

Introduction to Makefile

Following the example from the previous blog on the Introduction to GCC, I am going to show you how to makefile to simplify all those steps.

If for example, we have a directory structure like this.
/home/cpp/HelloWorld.cpp
         /HelloWorld.hpp
         /Main.cpp

* Makefile *
CC=g++
CFLAGS=-Wall
OBJ=Main.o HelloWorld.o

Main: $(OBJ)

clean:
    rm -rf Main *.o

1. To build
make
2. To clean
make clean
Here we use Makefile's implicit rules by only specifying the CC and CFLAGS implicit variables. For more information, see this link.

If now, we have a directory structure like this.
/home/cpp/lib/libhello.a
         /include/HelloWorld.hpp
         /Main.cpp
* Makefile *
CC=g++
INCLUDEDIR=include
LIBDIR=lib/libhello.a
CFLAGS=-Wall -I$(INCLUDEDIR)
OBJ=Main.o
DEPS=$(INCLUDEDIR)/HelloWorld.hpp

Main: $(OBJ)
    $(CC) -o Main $(OBJ) $(LIBDIR) $(CFLAGS) 

%.o: %.cpp $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

clean:
    rm -rf Main *.o
For more information about the automatic variables, such as $@, $<, see this link.

No comments:

Post a Comment