Passing target name to a dependency in makefile

半世苍凉 提交于 2019-12-23 09:38:34

问题


If I have the following rule in a 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.

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? 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)).


回答1:


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:

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



回答2:


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; each .o file is built using only the .c file corresponding to it; 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.


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.



来源:https://stackoverflow.com/questions/14573869/passing-target-name-to-a-dependency-in-makefile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!