【makefile】03 经典应用示例

经典应用示例

1. 文件结构

.
├── include
│   ├── module1
│   │   ├── mod1c1.hpp
│   │   └── mod1c2.hpp
│   ├── module2
│   │   ├── mod2c1.hpp
│   │   └── mod2c2.hpp
│   └── program.hpp
├── Makefile
└── src
    ├── module1
    │   ├── mod1c1.cpp
    │   └── mod1c2.cpp
    ├── module2
    │   ├── mod2c1.cpp
    │   └── mod2c2.cpp
    └── program.cpp

 

makefile文件:

 1 #
 2 # **************************************************************
 3 # *                Simple C++ Makefile Template                *
 4 # *                                                            *
 5 # * Author: Arash Partow (2003)                                *
 6 # * URL: http://www.partow.net/programming/makefile/index.html *
 7 # *                                                            *
 8 # * Copyright notice:                                          *
 9 # * Free use of this C++ Makefile template is permitted under  *
10 # * the guidelines and in accordance with the the MIT License  *
11 # * http://www.opensource.org/licenses/MIT                     *
12 # *                                                            *
13 # **************************************************************
14 #
15 
16 CXX      := -c++
17 CXXFLAGS := -pedantic-errors -Wall -Wextra -Werror
18 LDFLAGS  := -L/usr/lib -lstdc++ -lm
19 BUILD    := ./build
20 OBJ_DIR  := $(BUILD)/objects
21 APP_DIR  := $(BUILD)/apps
22 TARGET   := program
23 INCLUDE  := -Iinclude/
24 SRC      :=                      \
25    $(wildcard src/module1/*.cpp) \
26    $(wildcard src/module2/*.cpp) \
27    $(wildcard src/*.cpp)         \
28 
29 OBJECTS  := $(SRC:%.cpp=$(OBJ_DIR)/%.o)
30 DEPENDENCIES \
31          := $(OBJECTS:.o=.d)
32 
33 all: build $(APP_DIR)/$(TARGET)
34 
35 $(OBJ_DIR)/%.o: %.cpp
36     @mkdir -p $(@D)
37     $(CXX) $(CXXFLAGS) $(INCLUDE) -c $< -MMD -o $@
38 
39 $(APP_DIR)/$(TARGET): $(OBJECTS)
40     @mkdir -p $(@D)
41     $(CXX) $(CXXFLAGS) -o $(APP_DIR)/$(TARGET) $^ $(LDFLAGS)
42 
43 -include $(DEPENDENCIES)
44 
45 .PHONY: all build clean debug release info
46 
47 build:
48     @mkdir -p $(APP_DIR)
49     @mkdir -p $(OBJ_DIR)
50 
51 debug: CXXFLAGS += -DDEBUG -g
52 debug: all
53 
54 release: CXXFLAGS += -O2
55 release: all
56 
57 clean:
58     -@rm -rvf $(OBJ_DIR)/*
59     -@rm -rvf $(APP_DIR)/*
60 
61 info:
62     @echo "[*] Application dir: ${APP_DIR}     "
63     @echo "[*] Object dir:      ${OBJ_DIR}     "
64     @echo "[*] Sources:         ${SRC}         "
65     @echo "[*] Objects:         ${OBJECTS}     "
66     @echo "[*] Dependencies:    ${DEPENDENCIES}"

 

参考资料:

1. Simple C++ Makefile Example

2. makefile教程【C语言中文网】

posted @ 2021-10-21 22:17  苏格拉底的落泪  阅读(35)  评论(0编辑  收藏  举报