Auto tools makefile getting started

Basic the Makefile format

  • First make sure ~/.vimrc settings for tab spaces
1# define the .vimrc file to following contents
2cat ~/.vimrc
3set noexpandtab
4set autoindent
  • Small snippet Makefile contents
 1.DEFAULT_GOAL:=build
 2
 3fmt:
 4	echo "this is fmt...."
 5
 6.PHONY:vet
 7vet:fmt
 8	echo "this is vet..."
 9
10
11build:vet
12	echo "this is build..."
  • In the directory execute make should display the result.
1echo "this is fmt...."
2this is fmt....
3echo "this is vet..."
4this is vet...
5echo "this is build..."
6this is build...

More complicated example

 1#Ignore if has directory or file  same name in current directory
 2.PHONY:clean all
 3# Set the global variables to use in back  commands
 4CC=gcc
 5INCLUDE_DIR=
 6C_FLAGS=
 7
 8# All sub dirs except debug directory, because the debug directory to last compile
 9# Use awk to exclude debug
10SUBDIRS=$(shell ls -l | grep ^d | awk '{if($$9 != "debug") if($$9 != "include") print $$9}')
11
12#Lastly go to debug directory 
13#DEBUG=$(shell ls -l | grep ^d | awk '{if($$9 == "debug") print $$9}')
14
15#save current folder path to ROOT_DIR
16ROOT_DIR=$(shell pwd)
17
18#Finally application's name
19BIN=myapp
20
21#the obj file directory
22OBJS_DIR=debug/obj
23
24#the bin file directory
25BIN_DIR=debug/bin
26
27#store the all .c source file to CUR_SOURCE directory
28CUR_SOURCE=${wildcard *.c}
29
30#construct the all obj file with .c file
31CUR_OBJS=${patsubst %.c, %.o, $(CUR_SOURCE)}
32
33#export all variables to sub directory's Makefile
34export CC BIN OBJS_DIR BIN_DIR ROOT_DIR
35
36#order to exec target 
37all:$(SUBDIRS) $(CUR_OBJS) DEBUG
38
39
40# recurseive exec sub dirs make
41# per exec echo the sub dir
42$(SUBDIRS):ECHO
43	make -C $@
44
45DEBUG:ECHO
46	#go to debug directory exec make
47	make -C debug
48
49# echo the current sub dir
50ECHO:
51	@echo $(SUBDIRS)
52
53
54# compile the c file to obj save to relative obj dir
55$(CUR_OBJS):%.o:%.c
56	$(CC) -c $^ -o $(ROOT_DIR)/$(OBJS_DIR)/$@
57
58clean:
59	rm -rf $(OBJS_DIR)/*.o
60	rm -rf $(BIN_DIR)/*

Define the function and call it in sections

1build: prebuild
2	$(call print-target)
3	GOOS=linux GOARCH=amd64 go build -trimpath  -ldflags="-s -w"  -o detector main.go
4
5define print-target
6    @printf "Executing target: \033[36m$@\033[0m\n"
7endef

Reference

  • (makefile tutorial)[https://makefiletutorial.com/]
  • (balerter)[https://github.com/balerter/balerter/blob/master/Makefile]
  • (Self-Documented Makefile)[https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html]