Makefile for Projects with Subdirectories - JohnHau/mis GitHub Wiki

image

image

image

Practice Practice 1 - Write All Targets Directly To write a most simple makefile, we can code like:

image

image

image

image image

Practice 3 - Complete the makefile From above actions, we wrote a makefile that can adapt to various of projects. This part just some small modification to make our makefile better to look.

TARGET = kmusb

CC = gcc CFLAGS = -g

OUTDIR = ./bin DATADIR = ./data SUBDIR = semihost stream arg_parser DIR_OBJ = ./obj

INCS = $(wildcard .h $(foreach fd, $(SUBDIR), $(fd)/.h)) SRCS = $(wildcard .c $(foreach fd, $(SUBDIR), $(fd)/.c)) NODIR_SRC = $(notdir $(SRCS)) OBJS = $(addprefix $(DIR_OBJ)/, $(SRCS:c=o)) # obj/xxx.o obj/folder/xxx .o INC_DIRS = -I./ $(addprefix -I, $(SUBDIR)) LIBS = -largp LIB_DIRS = -L/usr/local/Cellar/argp-standalone/1.3/lib

PHONY := $(TARGET) $(TARGET): $(OBJS) $(CC) -o $(OUTDIR)/$@ $(OBJS) $(LIB_DIRS) $(LIBS)

$(DIR_OBJ)/%.o: %.c $(INCS) mkdir -p $(@D) $(CC) -o $@ $(CFLAGS) -c $< $(INC_DIRS)

PHONY += clean clean: rm -rf $(OUTDIR)/* $(DATADIR)/* $(DIR_OBJ)/*

PHONY += echoes echoes: @echo "INC files: $(INCS)" @echo "SRC files: $(SRCS)" @echo "OBJ files: $(OBJS)" @echo "LIB files: $(LIBS)" @echo "INC DIR: $(INC_DIRS)" @echo "LIB DIR: $(LIB_DIRS)"

.PHONY = $(PHONY)

Let’s leave alone the include library I added, since our main goal is to write a makefile to complie projects with subfolders. This makefile is copied from my projects.

You see, I adjust the way to write .PHONY.

This is a trick that I got from busybox. We add contents to the .PHONY wehen we write a new target is easier to maintain the makefile when it grows bigger and bigger.