几个简单适合小程序的Makefile,可直接拷贝使用,自己mark一下,这样长时间不用Makefile也不用去看手册了
0.只有一个文件
变量的定义,方便使用
CC = gcc
CCFLAGS = -O2 -s
BIN = test
OBJ = root_password_tool_win32.o
$(BIN) : $(OBJ)
$(CC) $(CCFLAGS) -o test $(OBJ)
$(OBJ) : root_password_tool_win32.c
$(CC) $(CCFLAGS) -c root_password_tool_win32.c
.PHONY : clean
clean :
-rm $(BIN) $(OBJ)
1.简单编译命令行程序,$(CC)前面是tab,不是space
一共五个文件:
test.c
md5.c md5.h
password.c password.h
main函数在test.c中,test.c文件include了md5.h和password.h
CC = gcc
CCFLAGS = -O2 -s
BIN = password
OBJ = md5.o password.o test.o
$(BIN) : $(OBJ)
$(CC) $(CCFLAGS) -o password $(OBJ)
md5.o : md5.c md5.h
$(CC) $(CCFLAGS) -c md5.c
password.o : password.c password.h
$(CC) $(CCFLAGS) -c password.c
test.o : test.c
$(CC) $(CCFLAGS) -c test.c
.PHONY : clean
clean :
-rm $(BIN) $(OBJ)
make # 编译得到password.exe,这里在windows下cigwin+mingw环境中编译
make clean # 清理编译生成的*.o等文件
2.使用g++编译win32程序的Makefile,其中简写了一些,可以对比1看看不同之处
说明:
(0)指定静态库目录,连接静态库libcomctl32.a编译程序
(1)编译windows资源文件(使用mingw的windres)
(2)使用-mwindows编译选项去除弹出的cmd窗口
CC = g++
-O2 : optimization option
-s : build small binary
-mwindows : use this option to remove the popping cmd window
CCFLAGS = -O2 -s -mwindows
BIN = test
WINDRES = windres
RES = resource.o
OBJ = main.o md5.o password.o $(RES)
where is your mingw library?
LIBPATH = ‘C:\Program Files\CodeBlocks\MinGW\lib'
LIBS=-L$(LIBPATH) -lcomctl32
RM = -rm
$(BIN): $(OBJ)
$(CC) $(CCFLAGS) -o $(BIN) $(OBJ) $(LIBS)
main.o: main.cpp
md5.o: md5.cpp md5.h
password.o: password.cpp password.h
编译资源文件
$(RES): resource.rc rpt.ico manifest
$(WINDRES) -o $(RES) resource.rc
.PHONY:clean
clean:
$(RM) $(BIN) $(OBJ)
3.编译静态库
其中一些$<,$^, $@是Makefile的自动化变量,详细了解可以看《跟我一起写Makefile》的第五章
CC = g++
OBJS = utp.o utp_utils.o
-g : for debug
CFLAGS = -g -O2 -Wall -DPOSIX
TARGET = libutp.a
.cpp.o:
$(CC) -c $(CFLAGS) $<
all: $(TARGET)
libutp.a: $(OBJS)
ar cru $@ $^
ranlib $@
.PHONY : clean
clean :
-rm *.o $(TARGET)
4.编译动态库
(0)windows下使用mingw编译dll动态库
CC = g++
OBJS = utp.o utp_utils.o
CCFLAGS = -fno-exceptions -fno-rtti -Wall -g -lwsock
TARGET = libutp.dll
all: $(TARGET)
$(TARGET): $(OBJS)
-rm -f $(TARGET)
$(CC) -shared -o $(TARGET) $(OBJS) -lws2_32
.cpp.o:
$(CC) -c -DPOSIX -fpic -I . -I utp_config_lib $(CCFLAGS) $<
.PHONY: clean
clean:
-rm -f $(OBJS) $(TARGET)
(1)linux下编译so动态库
CC = g++
OBJS = utp.o utp_utils.o
CCFLAGS = -fno-exceptions -fno-rtti -Wall -g
TARGET = libutp.so
all: $(TARGET)
$(TARGET): $(OBJS)
-rm -f $(TARGET)
g++ -shared -o $(TARGET) $(OBJS)
.cpp.o:
g++ -c -DPOSIX -fpic -I . -I utp_config_lib $(CCFLAGS) $<
.PHONY: clean
clean:
-rm -f $(OBJS) CCFLAGS
5.编译多个目标,0-2均是编译单个目标
(0) 添加头文件目录
(1) 使用自己编译的静态库libutp.a
CC = g++
CFLAGS = -g
LIBUTP_PATH = /home/actiontec/workspace/code_reading/third_party/libutp/lib
INCLUDES = -I${LIBUTP_PATH}
LIBS = -L$(LIBUTP_PATH) -lutp -lpthread -lrt
TARGET = all
all: server client
server: server.cpp
$(CC) $(CFLAGS) -o $@ $^ $(INCLUDES) $(LIBS)
client: client.cpp
$(CC) $(CFLAGS) -o $@ $^ $(INCLUDES) $(LIBS)
.PHONY : clean
clean:
-rm *.o server client
以上仅供参考