Saturday, March 17, 2012

Makefiles in C++ Project

A Makefile is used by the make command to create object or assembly files with rules, dependencies and target directory paths to direct output to a given set of pre-determined locations or items. A typical makefile is named Make1.make with an output of Make1.out for a project comprising of three cpp and one .h files.

# Make1.make -- this is a comment line, ignored by make utility
Make1.out : main1.o mylib.o openfile.o
g++ -o lab1.out main1.o mylib.o openfile.o
# above, we are saying lab1.out depends on main1.o, mylib.o and openfile.o
# and to create lab1.out we give the g++ command as shown on the next line
# which starts with a TAB although you cannot see that .
# note that the command : g++ -o lab1.out main1.o mylib.o openfile.o
# creates an executable file named lab1.out from the 3 object files respectively.
main1.o: main1.cpp openfile.h mylib.h
g++ -c main1.cpp
# above we are saying main1.o depends on main1.cpp openfile.h and mylib.h
# and to compile only main1.cpp if and only if main1.cpp or openfile.h or mylib.h
# have changed since the last creation of main1.o
mylib.o: mylib.cpp mylib.h
g++ -c mylib.cpp
# above we are saying mylib.o depends on mylib.cpp and mylib.h
# so if either mylib.cpp or mylib.h CHANGED since creating mylib.o
# comple mylib.cpp again
openfile.o: openfile.cpp openfile.h
g++ -c openfile.cpp
# above we are saying openfile.o depends on openfile.cpp and openfile.h
# so if either openfile.cpp or openfile.h has CHANGED since creating
# openfile.o, compile only (again) openfile.cpp
clean:
&nbps rm *.o Make1.out
# above we are stating how to run the rule for clean, no dependencies,
# what we want is when we ask to do a "make -f lab1.make clean"
# that will not do anything except remove executable and object files
# so we can "clean out" our directory of unneeded large files.
# we only do a make clean when we want to clean up the files.
# END OF MAKE FILE

No comments:

Post a Comment