复杂实例
#示例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.cpp int 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.h int pub(int a,char *ch,int b);
//3 main.cpp #include <iostream> #include <stdlib.h> #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