Makefile生成多个目标文件

时间:2021-12-22 06:13:02

有目录结构如下:

 mmap
├── Makefile
├── read
│   ├── Makefile
│   └── mmap_read.c
└── write
    ├── Makefile
    └── mmap_write.c


mmap 目录下面有 write 和 read 两个目录,mmap 目录下有一个 Makefile,两个子目录下各有一个 Makefile。


mmap 目录下 Makefile 内容如下:(下面的 \$$ 应当为 两个 $)

DIRS = write read

all: subdirs

.PHONY: subdirs clean

subdirs: $(DIRS)
	@for dir in $(DIRS); do [ ! -d \$$dir ] || make -C \$$dir || exit 1; done

clean:
	@echo $(DIRS)
	@for dir in $(DIRS); do [ ! -d \$$dir ] || make -C \$$dir clean || exit 1; done

mmap/write 目录下 Makefile 内容如下:

CC = gcc
LINK = gcc
CFLAGS = -g -pipe -Wall -Werror -Wextra -Wshadow
LIBS = 

SOURCES = $(wildcard *.c)
OBJECTS = $(patsubst %.c, %.o, $(SOURCES))
TARGET = mmap_write

first: all

%.o: %.c
	$(CC) -c $(CFLAGS) -o $@ $<

all: $(TARGET)

$(TARGET): $(OBJECTS)
	$(LINK) $(CFLAGS) $(LIBS) -o ../$(TARGET) $(OBJECTS)

.PHONY: clean

clean:
	rm -f $(OBJECTS) $(TARGET)

mmap/read 目录下 Makefile 内容如下:

CC = gcc
LINK = gcc
CFLAGS = -g -pipe -Wall -Werror -Wextra -Wshadow
LIBS = 

SOURCES = $(wildcard *.c)
OBJECTS = $(patsubst %.c, %.o, $(SOURCES))
TARGET = mmap_read

first: all

%.o: %.c
	$(CC) -c $(CFLAGS) -o $@ $<

all: $(TARGET)

$(TARGET): $(OBJECTS)
	$(LINK) $(CFLAGS) $(LIBS) -o ../$(TARGET) $(OBJECTS)

.PHONY: clean

clean:
	rm -f $(OBJECTS) $(TARGET)