复杂实例
#演示样例1:在上一个演示样例的基础上再添加一个可运行文件03test[改动之处已标红]
.PHONY: clean all
CC = gcc
CFLAGS = -Wall -g
BIN = 01test 02test 03test
SOURCES = $(BIN:=.c)
OBJECTS = $(BIN:=.o)
all: $(BIN)
01test: 01test.o
02test: 02test.o
03test: 03test.o
.c.o:
$(CC) $(CFLAGS) -c $< -o $@
clean:
-rm -rf $(BIN) $(OBJECTS)
#演示样例2:在演示样例1上为03test加入一个自编的头文件pub.h[改动之处已标红]
.PHONY: clean all
CC = gcc
CFLAGS = -Wall -g
BIN = 01test 02test 03test
SOURCES = $(BIN:=.c)
OBJECTS = $(BIN:=.o)
all: $(BIN)
01test: 01test.o
02test: 02test.o
03test: 03test.o pub.o
.c.o:
$(CC) $(CFLAGS) -c $< -o $@
clean:
-rm -rf $(BIN) $(OBJECTS)
一个比較复杂的综合演示样例
//1 pub.cppint pub(int a,char *ch,int b){ char c = ch[0]; switch(c) { case '+': return a+b; break; case '-': return a-b; break; case '*': return a*b; break; case '/': if (b != 0) { return a/b; } else { return -1; } break; default: return -1; break; } return 0;}
//2 pub.hint pub(int a,char *ch,int b);
//3 main.cpp#include#include #include "pub.h"using namespace std;int main(int argc,char *argv[]){ if (argc < 4) { cerr << "error" << endl; return -1; } cout << argv[1] << ' ' << argv[2] << ' ' << argv[3] << " = " << pub(atoi(argv[1]),argv[2],atoi(argv[3])) << endl; return 0;}
#4 Mackfile
.SUFFIXES:.cpp .o
CC=g++
SOURCE=main.cpp pub.cpp
OBJC=$(SOURCE:.cpp=.o) #将.cpp文件所有替换为.o文件
EXEC=mytest
all:$(OBJC)
$(CC) -o $(EXEC) $(OBJC)
.cpp.o:
$(CC) -o $@ -c $<
clean:
rm -rf $(OBJC)
附-假设一条语句在运行Mackfile文件时。不想打印出来,则在其前面加上@符号
比較专业的Makefile编写
#演示样例1
all: myapp
# Which compiler
CC = g++
# Where are include files kept
INCLUDE = .
# Options for development
FLAGS = -g -Wall -ansi
# Options for release
# CFLAGS = -O -Wall -ansi
.SUFFIXES:.cpp .o
SOURCE = main.cpp pub.cpp
OBJC = $(SOURCE:.cpp=.o)
EXEC = myapp
$(EXEC): ${OBJC}
$(CC) -o $(EXEC) $(OBJC)
.cpp.o:
$(CC) -o $@ -I$(INCLUDE) $(FLAGS) -c $<
clean:
rm -rf $(OBJC) $(EXEC)
#演示样例2-加入了install选项
all: myapp
# Which compiler
CC = g++
# Where to install
INSTDIR = /usr/local/bin/
# Where are inlude files kept
INCLUDE = .
# Options for development
CFLAGS = -g -Wall -ansi
# Options for release
# CFLAGS = -O -Wall -ansi
.SUFFIXES: .cpp .o
SOURCE = main.cpp pub.cpp
OBJECT = $(SOURCE:.cpp=.o)
EXEC = myapp
$(EXEC): $(OBJECT)
$(CC) -o $(EXEC) $(OBJECT)
.cpp.o:
$(CC) -I$(INCLUDE) $(CFLAGS) -o $@ -c $<
clean:
-rm -rf $(OBJECT)
install: $(EXEC)
@if [ -d $(INSTDIR) ] ; then \
cp $(EXEC) $(INSTDIR) ; \
chmod a+x $(INSTDIR)/$(EXEC) ; \
chmod og-w $(INSTDIR)/$(EXEC) ; \
echo "Installed in $(INSTDIR)" ; \
else \
echo "Sory, $(INSTDIR) does not exist." ; \
fi