Table of Contents
Makefiles
Makefiles are very useful to automate compilation of multi-file projects in c/c++ with Linux.
Syntax
- variables:
<VARIABLE>=<string> # init $(<VARIABLE>) # get content
- targets:
<target>: <prerequisite-targets> <code-to-execute>
- template targets:
%.o:%.cpp <code-to-execute>
- automatic variables (complete list)::
$@
: target$^
: list of requirements$<
: first requirement$(MAKECMDGOALS)
: make argument
- functions (complete list):
$(subst from,to,text)
$(filter-out <list>, <list>)
- Mini Example
COMPILO=g++ SRCSCPP = $(wildcard src/*.cpp) OBJS = $(patsubst %.cpp,build/%.o,$(notdir $(SRCSCPP))) prog: $(OBJS) $(COMPILO) -o build/$@ $(OBJS) build/%.o:%.cpp $(COMPILO) -c -o $@ $^
Example
INCLUDE= \ -I/usr/include \ -I/usr/local/include \ -I. \ `pkg-config --cflags libglade-2.0` BIN_PATH=./ LIBS= \ `pkg-config --libs libglade-2.0` \ `pkg-config --libs gtk+-2.0` \ -export-dynamic LIBS_PATH= \ -L/lib \ -L/usr/lib \ -L/usr/local/lib \ -L. COMPILO=g++ FLAGS= -c -g -Wall -ansi -pedantic #FLAGS= -c -ansi -pedantic OBJ= \ file1.o \ file2.o # cibles : monprog: $(OBJ) $(COMPILO) -o $(BIN_PATH)monprog $(OBJ) $(LIBS_PATH) $(LIBS) clean : rm -f *.o clear : rm -f *.o monprog # compilation des sources : file1.o : file1.cpp file1.h $(COMPILO) $(FLAGS) $(INCLUDE) -o file1.o file1.cpp file2.o : file2.cpp file2.h $(COMPILO) $(FLAGS) $(INCLUDE) -o file2.o file2.cpp
pkg-config
When using libraries, pkg-config is very useful :
pkg-config --cflags libxml++-2.6 pkg-config --libs libxml++-2.6