簡體   English   中英

多個目標但相同的依賴

[英]Multiple targets but same dependency

這是我的 makefile 的一部分:

SRC     =   ./
DIRS    =   src libs/maths libs/struct
BIN_DIR =   ./bin/

SRC_DIRS=   $(foreach dir, $(DIRS), $(addprefix $(SRC), $(dir)))
SRC_TEST=   $(sort $(SRC_DIRS))

SRCS    =   $(foreach msrc, $(SRC_DIRS), $(wildcard $(msrc)/*.c))

DEL_PRE =   $(foreach target, $(SRCS), $(notdir $(target)))
ADD_PRE =   $(foreach target, $(DEL_PRE), $(addprefix $(BIN_DIR), $(target)))
OBJS    =   $(ADD_PRE:.c=.o)

.PHONY: all clean re

all:        $(EXEC)

$(EXEC):    $(OBJS)
    $(CC) $(OBJS) -o $@ $(LDLIBS)

$(OBJS):    $(SRCS)
    $(CC) -o $@ -c $<

當我使用 make all 時,我有輸出:

gcc -o bin/main.o -c src/main.c
gcc -o bin/cosin.o -c src/main.c
gcc -o bin/pears.o -c src/main.c
gcc -o bin/outil.o -c src/main.c
gcc -o bin/verif.o -c src/main.c

但是我想為每個目標分配依賴項:

gcc -o bin/main.o -c src/main.c
gcc -o bin/cosin.o -c libs/maths/cosin.c
gcc -o bin/pears.o -c libs/maths/pears.c
gcc -o bin/outil.o -c libs/struct/outil.c
gcc -o bin/verif.o -c libs/struct/verif.c

我該如何解決?

這似乎是一個非常普遍的誤解。 我昨天剛剛有效地回答了同樣的問題。 我不確定它來自哪里或如何對抗它。

這個規則:

$(OBJS):    $(SRCS)
       $(CC) -o $@ -c $<

不會神奇地結合起來的內容OBJS變量和SRCS變量,以弄清楚他們如何匹配。 變量引用被簡單地擴展,結果是這樣的:

bin/main.o bin/cosin.o ... : src/main.c libs/maths/cosin.c ...
       $(CC) -o $@ -c $<

這就像你寫的一樣:

bin/main.o : src/main.c libs/maths/cosin.c ...
       $(CC) -o $@ -c $<
bin/cosin.o : src/main.c libs/maths/cosin.c ...
       $(CC) -o $@ -c $<
...

現在,您可能會明白為什么要編譯相同的文件:在每個規則中,您都有相同的先決條件,因此$<始終是第一個,也就是src/main.c

有多種方法可以解決這個問題,但是如果您真的希望將來自不同目錄的所有源文件編譯到同一目錄中的目標文件中,那么您的工作就更難了,因為沒有將它們全部匹配的通用模式。 在這種情況下,最簡單的做法是使用VPATH 進行目錄搜索:將上述規則替換為:

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

然后告訴 make 如何找到你的源文件,像這樣:

VPATH := $(sort $(dir $(SRCS))

請注意,此方法不能用於任何本身是 make 預期創建的輸出的源文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM