不同输出目录的gcc依赖项生成
我正在使用gcc生成依赖文件,但是我的构建规则将输出放入子目录中。有没有办法告诉gcc将我的子目录前缀放在它为我生成的依赖文件中?
gcc $(INCLUDES) -E -MM $(CFLAGS) $(SRC) >>$(DEP)
解决方案
如果gcc有这样做的论据,我不知道它是什么。我们最终通过sed传递了依赖项输出,以将所有出现的.o重写为$ {OBJDIR} /。o
好的,只是为了确保我正确地回答了这个问题:我假设我们有包含test.h的test.c,并且我们想生成subdir / test.d(而不生成subdir / test.o), subdir / test.d包含
subdir/test.o: test.c test.h
而不是
test.o: test.c test.h
这就是我们现在得到的。是对的吗?
我无法提出一种简单的方法来准确地完成要求。但是,请查看http://www.gnu.org/software/gcc/news/dependencies.html,如果要在生成.o文件的同时创建.d文件,则可以使用
gcc $(INCLUDES) -MMD $(CFLAGS) $(SRC) -o $(SUBDIR)/$(OBJ)
(考虑到SRC = test.c,SUBDIR = subdir和OBJ = test.o),这将创建subdir / test.o和subdir / test.d,其中subdir / test.d包含上述所需的输出。希望能有所帮助。
- 如果我们不将输出放置在当前目录中,[GNU] make就会生气。我们真正应该做的是在构建目录中运行make,然后使用VPATH make变量查找源代码。如果我们对编译器撒谎,迟早会报仇。
- 如果我们坚持要在其他目录中生成对象和依赖项,则需要使用Emile回答的-o参数。
答案在GCC手册中:使用-MT
标志。
-MT target Change the target of the rule emitted by dependency generation. By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as .c, and appends the platform's usual object suffix. The result is the target. An -MT option will set the target to be exactly the string you specify. If you want multiple targets, you can specify them as a single argument to -MT, or use multiple -MT options. For example, -MT '$(objpfx)foo.o' might give $(objpfx)foo.o: foo.c
我假设我们正在使用GNU Make和GCC。首先添加一个变量来保存依赖文件列表。假设我们已经拥有列出我们所有来源的资料:
SRCS = \ main.c \ foo.c \ stuff/bar.c DEPS = $(SRCS:.c=.d)
然后在生成文件中包含生成的依赖项:
include $(DEPS)
然后添加以下模式规则:
# automatically generate dependency rules %.d : %.c $(CC) $(CCFLAGS) -MF"$@" -MG -MM -MP -MT"$@" -MT"$(<:.c=.o)" "$<" # -MF write the generated dependency rule to a file # -MG assume missing headers will be generated and don't stop with an error # -MM generate dependency rule for prerequisite, skipping system headers # -MP add phony target for each header to prevent errors when header is missing # -MT add a target to the generated dependency
" $ @"是目标(在:左边的东西)," $ <"是前提(在:右边的东西)。表达式" $(<:. c = .o)"将.c扩展名替换为.o。
这里的窍门是通过两次添加-MT来生成具有两个目标的规则。这使得.o文件和.d文件都依赖于源文件及其头文件;这样,只要更改了相应的.c或者.h文件,依赖文件就会自动重新生成。
如果缺少头文件,则-MG和-MP选项可防止make出现异常。