Improved version of commonly used Makefile

Makefile improvements, automatically traverse all c files in the specified directory, no need to manually add in Makefile...
Makefile detailed analysis, please refer to Makefile learning

Take the following file structure as an example to illustrate the Makefile

  • File structure
eric@eric-PC:~/Documents/work/linux-c/http(副本)$ tree
.
├── libmbedtls
│   ├── libmbedcrypto.a
│   ├── libmbedtls.a
│   └── libmbedx509.a
├── Makefile
└── src
    ├── httpclient
    │   ├── httpclient.c
    │   └── httpclient.h
    ├── json
    │   ├── cJSON.c
    │   └── cJSON.h
    └── main.c

4 directories, 9 files

  • Makefile
######################################
# eric
######################################

## 指定编译工具
CC	= gcc
CPP	= g++
RM	= rm -rf

## 源文件路径(默认检索3层)
SRC_PATH	:= ./src
DIRS	:= $(shell find $(SRC_PATH) -maxdepth 3 -type d)

## 目标文件名称
TARGET	:= main

## 获取所有.c文件路径
SRCS	+= $(foreach dir, $(DIRS), $(wildcard $(dir)/*.c))
SRCPPS	+= $(foreach dir, $(DIRS), $(wildcard $(dir)/*.cpp))

## 所有对应目标文件
OBJS	:= $(SRCS:.c=.o) $(SRCPPS:.cpp=.o)

## 所有用到的库
LIBS	:= pthread m mbedtls mbedcrypto mbedx509

## 指定头文件路径
INCLUDE_PATH	:= . $(DIRS)

## 指定库文件路径
LIB_PATH	:= /lib ./libmbedtls

## 编译参数初始化
CFLAGS		:= -g -O3 #-Wall

## 加载头文件路径
CFLAGS		+= $(foreach dir, $(INCLUDE_PATH), -I$(dir))
CFLAGS 		+=  `pkg-config --cflags --libs opencv` 

## 加载库文件路径
LDFLAGS		+= $(foreach libdir, $(LIB_PATH), -L$(libdir))

## 加载库文件
LDFLAGS 	+= $(foreach lib, $(LIBS), -l$(lib))


.PHONY:all
all: $(TARGET) 
 
$(TARGET) :$(OBJS)
	@$(CC) $(CFLAGS) -o $@ $(OBJS) $(LDFLAGS)
	@#$(RM) $(OBJS)
	@echo =============================
	@echo $(TARGET) ok

%.o	: %.c
	@echo $@...
	@$(CC) -c $(CFLAGS) $< -o $@
	
%.o	: %.cpp
	@echo $@...
	@$(CPP) -c $(CFLAGS) $< -o $@ 
	
# %.o	: %.S
#     $(CC) -c $(CFLAGS) $< -o $@
 
.PHONY:clean
clean:
	$(RM) $(OBJS) $(TARGET)
  • make && make clean
eric@eric-PC:~/Documents/work/linux-c/http(副本)$ make clean
rm -rf ./src/main.o ./src/json/cJSON.o ./src/httpclient/httpclient.o main 
eric@eric-PC:~/Documents/work/linux-c/http(副本)$ make
src/main.o...
src/json/cJSON.o...
src/httpclient/httpclient.o...
=============================
main ok
eric@eric-PC:~/Documents/work/linux-c/http(副本)$ tree
.
├── libmbedtls
│   ├── libmbedcrypto.a
│   ├── libmbedtls.a
│   └── libmbedx509.a
├── main
├── Makefile
└── src
    ├── httpclient
    │   ├── httpclient.c
    │   ├── httpclient.h
    │   └── httpclient.o
    ├── json
    │   ├── cJSON.c
    │   ├── cJSON.h
    │   └── cJSON.o
    ├── main.c
    └── main.o

4 directories, 13 files

Only this record

Guess you like

Origin blog.csdn.net/pyt1234567890/article/details/109329761
Recommended