Makefile是在Linux开发常见的代码编译规则工具。

C和C++简单通用型Makefile

  Makefie在开发中是十分重要的工具,但并不是天天都要写Makefile,关于语法会有遗忘,有时需要写一些代码做简单的demo测试时,可以直接使用。默认头文件*.h放在include目录下,*.c*.cpp放在src目录下。

Makefile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Source file.
# Automatically finds all.c and.cpp files and defines the target as a.o file with the same name.
# The *.c save in src directory.
SOURCE := $(wildcard ./src/*.c) $(wildcard ./src/*.cpp)
OBJS := $(patsubst %.c,%.o,$(patsubst %.cpp,%.o,$(SOURCE)))

# Target you can change test to what you want.
TARGET := demo

# Compile and lib parameter.
# Build c project .
# CC := gcc
# Build c++ project.
CC := g++
LIBS := -lpthread -lm
LDFLAGS :=
DEFINES :=
# The *.o save in include directory.
INCLUDE := -I ./include
CFLAGS := -Wall $(DEFINES) $(INCLUDE) -std=c++11
CXXFLAGS:= $(CFLAGS) -DHAVE_CONFIG_H


.PHONY : everything objs clean veryclean rebuild

everything : $(TARGET)

all : $(TARGET)

objs : $(OBJS)

rebuild: veryclean everything

clean :
rm -fr ./src/*.so
rm -fr ./src/*.o
rm -rf $(TARGET)

veryclean : clean
rm -fr $(TARGET)

$(TARGET) : $(OBJS)
$(CC) -o $@ $(OBJS) $(LDFLAGS) $(LIBS)