Automated GNU Makefile
Join the DZone community and get the full member experience.Join For Free
A simple automated GNU Makefile to build and link c/c++/asm projects. All the variables that need to be tweaked are located at the begining: PROGNAME: the name of the executable to be built CC: the C compiler CPP: the C++ compiler ASM: the assambler LD: the linker This searches for all *.c, *.cpp and *.s files and compiles them into objects. It then links all the files into a single executable. The strip rule is used to strip all unwanted symbols from the resulting executable. This usually results in a significant (think 40%) size optimisation.
$(VERBOSE).SILENT: PROGNAME = prog CC = gcc CC += -c CPP = g++ CPP += -c ASM = nasm ASM += -f elf -d ELF_TYPE LD = g++ OBJFILES = $(patsubst %.c,%.o,$(wildcard *.c)) OBJFILES += $(patsubst %.s,%.o,$(wildcard *.s)) OBJFILES += $(patsubst %.cpp,%.o,$(wildcard *.cpp)) all: $(PROGNAME) clean: @echo "Cleaning object files" @echo " rm -f *.o" rm -f *.o @echo "Cleaning backups" @echo " rm -f *~" rm -f *~ @echo "Removing programme" @echo " rm -f "$(PROGNAME) rm -f $(PROGNAME) %.o: %.s @echo "Assambling "$@ @echo " ASM "$< $(ASM) $< %.o: %.c @echo "Compiling "$@ @echo " CC "$< $(CC) $< %.o: %.cpp @echo "Compiling "$@ @echo " CPP "$< $(CPP) $< $(PROGNAME): $(OBJFILES) @echo "Linking "$@ @echo " LD -o "$(PROGNAME)" "$(OBJFILES) $(LD) -o $(PROGNAME) $(OBJFILES) strip: $(PROGNAME) @echo "Stripping "$(PROGNAME) echo -n "Size of "$(PROGNAME)" before strip is " ls -sh $(PROGNAME) | cut -d' ' -f1 @echo " strip "$(PROGNAME) strip $(PROGNAME) echo -n "Size of "$(PROGNAME)" after strip is " ls -sh $(PROGNAME) | cut -d' ' -f1 nothing: @echo "Nothing to do; quitting :(" @echo "HINT: Try make all"
Opinions expressed by DZone contributors are their own.