Among the actual program file is large, this time to classify files, divided into header files, source files, object files, executable files. That is usually a file by file type them in a different directory, this time Makefile requires unified management of these files, the production target files in the target directory, the executable file into the executable directory.
DIR_INC = ./include DIR_SRC = ./src DIR_OBJ = ./obj DIR_BIN = ./bin SRC = $(wildcard ${DIR_SRC}/*.c) OBJ = $(patsubst %.c,${DIR_OBJ}/%.o,$(notdir ${SRC})) TARGET = main BIN_TARGET = ${DIR_BIN}/${TARGET} CC = gcc CFLAGS = -g -Wall -I${DIR_INC} ${BIN_TARGET}:${OBJ} $(CC) $(OBJ) -o $@ ${DIR_OBJ}/%.o:${DIR_SRC}/%.c $(CC) $(CFLAGS) -c $< -o $@ .PHONY:clean clean: find ${DIR_OBJ} -name *.o -exec rm -rf{}
Explained as follows:
(1) Makefile symbols in $ @, $ ^, $ <meaning:
$ @ represents the target file
$ ^ represents all dependent files
$ <represents a dependency file
$ express new list also rely on documents than the target?
(2) wildcard, notdir, patsubst meaning:
wildcard: wildcard expansion
notdir: Remove Path
patsubst: Alternatively Wildcard
SRC = $(wildcard *.c)
Equal to the specified compile all .c files in the current directory, if there are subdirectories, such as subdirectories as inc, then add a wildcard function, like this:
SRC = $(wildcard *.c) $(wildcard inc/*.c)
gcc -o hello hello.c -I /home/hello/include -L /home/hello/lib -lworld
The above sentence said in compiling hello.c -I / home / hello / include express the / home / hello / include directory as the first directory to find header files,
Looking order is: / home / hello / include -> / usr / include -> / usr / local / include
-L / home / hello / lib represents the / home / hello / lib directory as the first to find catalog file,
Looking order is: / home / hello / lib -> / lib -> / usr / lib -> / usr / local / lib
-lworld looking libworld.so represent dynamic library files in lib path above in (if gcc compiler option to join the "-static" looking libworld.a represents static library file)