head.h
#ifndef HEAD_H_
#define HEAD_H_
#ifdef _cplusplus
extern "C"{
#endif
void File2Print();
#ifdef _cplusplus
}
#endif
#endif
file1.c
#include <stdio.h>
#include "head.h"
int main(){
printf("print file 1 $$$$$$$$$$$$$$$$$$\n");
File2Print();
return 0;
}
file2.c
#include "head.h"
void File2Print(){
printf("Print file2 **************\n");
}
makefile-1
helloworld:file1.o file2.o // helloworld依賴 file1.o 和 file2.o 兩個目標文件
gcc file1.o file2.o -o helloworld // 編譯helloworld可執行文件 -o 指定的目標文件
file1.o:file1.c
gcc -c file1.c -o file1.o // -c 只把源碼文件編譯成目標文件
file2.o:file2.c head.h //file2.c中無stdio.h 必須加 head.h
gcc -c file2.c -o file2.o
clean: //make clean 會刪除
rm -rf *.o helloworld
命令模式
A:B
(tab) <command>
makefile-2
OBJS = file1.o file2.o
CC = gcc
CFLAGS = -Wall -O -g //輸出所有警告信息 在編譯時進行優化 編譯debug版本helloworld:$(OBJS)
$(CC) $(OBJS) -o helloworld
file1.o:file1.c
$(CC) $(CFLAGS) -c file1.c -o file1.o
file2.o:file2.c head.h
$(CC) $(CFLAGS) -c file2.c -o file2.o
clean:
rm -rf *.o helloworld
makefile-3
XX = g++
CC = gcc
CFLAGS = -Wall -O -g
TARGET = ./helloworld
%.o:%.c
$(CC) $(CFLAGS) -c $< -o $@ // $@ 擴展爲當前規則的目的文件名 $< 擴展爲依靠列表中的第一個依靠文件 $^整個依靠的列表
%.o:%.cpp
$(XX) $(CFLAGS) -c $< -o $@
SOURCES = $(wildcard *.c *.cpp) //wildcard 產生一個所有以.c, .cpp結尾的文件的列表,然後存入變量裏
OBJS = $(patsubst %.c, %.o, $(patsubst %.cpp, %.o, $(SOURCES))) //匹配替換,第一個是需要匹配的樣式,第二個是用什麼來替換它,第三個是一個需要被處理的由空格分隔的列表
$(TARGET):$(OBJS)
$(XX) $(OBJS) -o $(TARGET)
chmod a+x $(TARGET)
clean:
rm -rf *.o helloworld