假设有如下程序:
hellomake.c | hellofunc.c | hellomake.h |
#include "hellomake.h" int main() { // call a function in another file myPrintHelloMake(); return(0); } |
#include <stdio.h> #include "hellomake.h" void myPrintHelloMake(void) { printf("Hello makefiles!\n"); return; } |
/* example include file */ void myPrintHelloMake(void); |
使用命令行编译
gcc -o hellomake hellomake.c hellofunc.c
缺点:
1. 如果有更多的文件,gcc命令复杂
2. 如果只改动某个文件,所有文件都需要重新编译
Makefile 版本1
hellomake: hellomake.c hellofunc.c
gcc -o hellomake hellomake.c hellofunc.c
Makefile 文件中包含一组用编译应用程序的规则,make 看到的第一项规则叫默认规则。
规则由三部分组成: target, prerequiste, command.
target: prereq1 prereq2
commands
缺点:
* 所有代码文件都在同一目录中
Makefile 版本2
CC=gcc CFLAGS=-I. hellomake: hellomake.o hellofunc.o $(CC) -o hellomake hellomake.o hellofunc.o -I.
Makefile 版本3
CC=gcc CFLAGS=-I. DEPS = hellomake.h %.o: %.c $(DEPS) $(CC) -c -o [email protected] $< $(CFLAGS) hellomake: hellomake.o hellofunc.o gcc -o hellomake hellomake.o hellofunc.o -I.
Makefile 版本5
CC=gcc CFLAGS=-I. DEPS = hellomake.h OBJ = hellomake.o hellofunc.o %.o: %.c $(DEPS) $(CC) -c -o [email protected] $< $(CFLAGS) hellomake: $(OBJ) gcc -o [email protected] $^ $(CFLAGS)
Makefile 版本6
IDIR =../include CC=gcc CFLAGS=-I$(IDIR) ODIR=obj LDIR =../lib LIBS=-lm _DEPS = hellomake.h DEPS = $(patsubst %,$(IDIR)/%,$(_DEPS)) _OBJ = hellomake.o hellofunc.o OBJ = $(patsubst %,$(ODIR)/%,$(_OBJ)) $(ODIR)/%.o: %.c $(DEPS) $(CC) -c -o [email protected] $< $(CFLAGS) hellomake: $(OBJ) gcc -o [email protected] $^ $(CFLAGS) $(LIBS) .PHONY: clean clean: rm -f $(ODIR)/*.o *~ core $(INCDIR)/*~
使用工作区
all
install
clean
disclean
TAGS
info
check
在BSD与Linux平台通用的makefile
编译 make
Debug make DEBUG=1
BSD gmake BSD=1
# Makefile for utelnetd # # Configure this with the following environment variables: # # where to install INSTDIR := /usr/local/bin/ # GNU target string CROSS := # where to find login program ifneq ("", "$(BSD)") LOGIN := /usr/bin/login else LOGIN := /bin/login endif ifneq ("", "$(BSD)") CORE := utelnetd.core else CORE := core endif # nothing to configure below this line... ---8<---8<---8<--- PROGS = utelnetd INSTMODE = 0755 INSTOWNER = root INSTGROUP = root OBJS = utelnetd.o CC = $(CROSS)gcc INSTALL = install CFLAGS += -I. -pipe -DSHELLPATH=\"$(LOGIN)\" -Wall ifneq ("","$(DEBUG)") CFLAGS += -DDEBUG -g -Os STRIP = \# else CFLAGS += -fomit-frame-pointer STRIP = $(CROSS)strip endif ifeq ("1", "$(BSD)") CFLAGS += -DBSD endif all: $(PROGS) $(PROGS): $(OBJS) $(CC) $(LDFLAGS) $^ $(LDLIBS) -o [email protected] $(STRIP) --remove-section=.comment --remove-section=.note [email protected] .PHONY: install install: $(PROGS) $(INSTALL) -d $(INSTDIR) $(INSTALL) -m $(INSTMODE) -o $(INSTOWNER) -g $(INSTGROUP) $(PROGS) $(INSTDIR) .PHONY: clean clean: rm -f $(PROGS) *.o $(CORE)
GNU make 官方文档 https://www.gnu.org/software/make/manual/make.html