Makefile模板
一.可执行程序
########################################## # Makefile for simple programs # # 编译可执行程序 ########################################### INC= LIB= -lpthread CC=gcc CC_FLAG=-Wall #以下test与要编译的c源文件的名称对应,此处要编译的是test.c文件 PRG=test OBJ=test.o $(PRG):$(OBJ) $(CC) $(INC) -o $@ $(OBJ) $(LIB) .SUFFIXES: .c .o .cpp .cpp.o: $(CC) $(CC_FLAG) $(INC) -c $*.cpp -o $*.o .PRONY:clean clean: @echo "Removing linked and compiled files......" rm -f $(OBJ) $(PRG)
二. 静态库
############################################################# # Makefile for static library. # # 编译静态链接库.a # ############################################################# CC = g++ CC_FLAG = -D_NOMNG -D_FILELINE AR = ar #set your inc and lib INC = LIB = -lpthread -L./ -ltest #make target lib and relevant obj PRG = libtest.a OBJ = test.o #all target all:$(PRG) $(PRG):$(OBJ) ${AR} rv ${PRG} $? .SUFFIXES: .c .o .cpp .cpp.o: $(CC) $(CC_FLAG) $(INC) -c $*.cpp -o $*.o .PRONY:clean clean: @echo "Removing linked and compiled files......" rm -f $(OBJ) $(PRG)
三.动态库
############################################################# # Makefile for shared library. # # 编译动态链接库.so ############################################################# #set your own environment option CC = gcc CC_FLAG = -fpic #set your inc and lib INC = LIB = -lpthread -L./ #make target lib and relevant obj PRG = libtest.so OBJ = test.o #all target all:$(PRG) $(PRG):$(OBJ) $(CC) -shared -o $@ $(OBJ) $(LIB) .SUFFIXES: .c .o .c.o: $(CC) $(CC_FLAG) $(INC) -c $*.c -o $*.o .PRONY:clean clean: @echo "Removing linked and compiled files......" rm -f $(OBJ) $(PRG)
附录: 以下为测试源程序test.c
#include<stdio.h> #include<limits.h> #define FUN #ifndef FUN #define STR(s) #s #else #define CONS(a,b) (int)(a##e##b) #endif #define OUTPUT(A) printf(A) typedef struct student{ int id; char* name; }student,*PtrStu; main(){ /** linux内核结构体初始化方式,在ubuntu系统下不支持,可以使用在CentOS或Redhat系统下 student st[3] = { [0] = { .id = 123, .name = "zhangming", }, [1] = { .id = 456, .name = "lisi", }, [2] = { .name = "hello", .id = 789, } }; **/ student st[3] = {{123,"zhangming"},{456,"lisi"},{789,"hello"}}; int i = 0; int length = sizeof(st)/sizeof(student); student* pstu = (student*)&st; for(;(pstu+i)!=(student*)(st + length);i++){ printf("id:%d name: %s\n",(pstu+i)->id,(pstu[i]).name); } //printf(STR(vck\n)); //输出字符串“vck” //OUTPUT(STR(vck\n)); //输出字符串“vck” printf("value: %d\n",CONS(2,3)); //0x2e3 输出value: 2000 }
测试效果截图如下: