简体   繁体   English

将目标名称传递给makefile中的依赖项

[英]Passing target name to a dependency in makefile

If I have the following rule in a makefile: 如果我在makefile中有以下规则:

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

Every file matching the prefix ./obj/ and sufix .o will have its stem passed to % , so I can provide some dependencies based on its name. 每个匹配前缀./obj/./obj/ .o都会将其传递给% ,因此我可以根据其名称提供一些依赖项。

But, suppose I have this kind of rule, which I specify one by one the targets I want: 但是,假设我有这样的规则,我逐一指定我想要的目标:

OBJECTS=abc.o bca.o cba.o
$(OBJECTS): $(SRC)/%.c
    $(CC) -c -o $@ $< $(CFLAGS)

How do I make the % stem actually work for the current target name make is executing? 如何使% stem实际上对当前目标名称make有效 Just using % doesn't work, neither $@ . 只使用%不起作用,也不是$@

Note that I'm trying to write the actual target name to its own dependency. 请注意,我正在尝试将实际目标名称写入其自己的依赖项。 For example, when make is executing the rule for abc.o , it would include $(SRC)/abc.c and just it (something like $(patsubst %.o, $(SRC)/%.c, MAGIC_TARGET_NAME_VARIABLE) ). 例如,当make正在执行abc.o的规则时,它将包括$(SRC)/abc.c和它(类似于$(patsubst %.o, $(SRC)/%.c, MAGIC_TARGET_NAME_VARIABLE) ) 。

You can just replace this rule: 您可以替换此规则:

$(OBJECTS): $(SRC)/%.c

with: 有:

$(OBJECTS) : %.o : $(SRC)/%.c

You will need to add the $(OBJ) to the -o part of the recipe if you still want them built there: 如果您仍希望在其中构建$(OBJ) ,则需要将$(OBJ)添加到配方的-o部分:

$(OBJECTS) : %.o : $(SRC)/%.c
     $(CC) -c -o $(OBJ)/$@ $< $(CFLAGS)

I'm not completely clear on what you're asking, but I think this accomplishes what you're trying to do: 我不清楚你在问什么,但我认为这可以完成你想要做的事情:

OBJECTS=abc.o bca.o cba.o

.PHONY: all
all: $(OBJECTS:%=obj/%)

$(OBJ)/%.o: $(SRC)/%.c
    echo $(CC) -c -o $@ $< $(CFLAGS)

All .o files are built; 所有.o文件都已构建; each .o file is built using only the .c file corresponding to it; 每个.o文件只使用与之对应的.c文件构建; and if you want to refer to the list of all object files or source files in the command for compiling a .o file, then you can reference ${OBJECTS} directly. 如果要在编译.o文件的命令中引用所有目标文件或源文件的列表,则可以直接引用${OBJECTS}


If this isn't what you're trying to do, you'll be able to get a better answer by listing the input files you have, the output files you want to make, the input dependencies of each output file, and what compilation command you want to execute for each output file. 如果这不是您想要做的,您将能够通过列出您拥有的输入文件,您想要输出的文件,每个输出文件的输入依赖项以及编译内容来获得更好的答案。要为每个输出文件执行的命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM