So today I found some usefulness of Makefile( it is always useful; just that it does not click yet for me until now )
1. Resolving include path
Earlier, I found myself tired of looking over the directory to include in my cpp files. I would write something like this:
#include ../../include/Math/blah.h #include ../../include/src/blah2.h
Isn’t is gruelsome ? Don’t I just need to know the fact that it exists somewhere and I just need to spell out the name and the program, compiler or whatever will find it out for me. It turns out there is an option for that : -I/dir/ and Makefile makes Laziness to another level.
#include "blah2.h" #include "blah.h"
2. Some syntax smartness:
– A target can have parameter and you expand the parameters with $^. For i.e: I need to compile all the cpp in a directory, so I make a variable SRC=$(wildcard *.cpp) which at runtime will find all the cpp for me then I just need to pass SRC to target parameter and invoke it with $^. Sweet. very simple.
SRC=$(wildcard *.cpp) compile: $(SRC) $(CC) $(CFLAGS) $^
– To spell out the target name , use $@. For i.e to compile to object file with the same name as target : $(CC) $(CFLAGS) $^ -o $@.
Here is the Makefile template I’m using so far
INC_DIR=../../include/Math/ CC=g++ -std=c++11 CFLAGS=-c -Wall -I$(INC_DIR) SRC=$(wildcard *.cpp) #$^: expanding the parameter #$@: use the target name #math.o: compile # $(CC) $(CFLAGS) $^ -o $@ compile: $(SRC) $(CC) $(CFLAGS) $^ clean: rm *.o *.out