如何仅使用一个makefile在子目录中生成带有源代码的Makefile [英] How to generate a Makefile with source in sub-directories using just one makefile

查看:172
本文介绍了如何仅使用一个makefile在子目录中生成带有源代码的Makefile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在很多子目录中都有源代码,

I have source in a bunch of subdirectories like:

src/widgets/apple.cpp
src/widgets/knob.cpp
src/tests/blend.cpp
src/ui/flash.cpp

在项目的根目录中,我想使用以下规则生成单个Makefile:

In the root of the project I want to generate a single Makefile using a rule like:

%.o: %.cpp
   $(CC) -c $<

build/test.exe: build/widgets/apple.o build/widgets/knob.o build/tests/blend.o src/ui/flash.o
   $(LD) build/widgets/apple.o .... build/ui/flash.o -o build/test.exe

当我尝试此操作时,找不到关于build/widgets/apple.o的规则.我可以更改一些内容,以便在需要生成build/widgets/apple.o时使用%.o:%.cpp吗?

When I try this it does not find a rule for build/widgets/apple.o. Can I change something so that the %.o: %.cpp is used when it needs to make build/widgets/apple.o ?

推荐答案

原因是您的规则

%.o: %.cpp
       ...

期望.cpp文件位于与建筑物.o相同的目录中.由于您所用的test.exe取决于build/widgets/apple.o(等等),因此make期望apple.cpp为build/widgets/apple.cpp.

expects the .cpp file to reside in the same directory as the .o your building. Since test.exe in your case depends on build/widgets/apple.o (etc), make is expecting apple.cpp to be build/widgets/apple.cpp.

您可以使用VPATH解决此问题:

You can use VPATH to resolve this:

VPATH = src/widgets

BUILDDIR = build/widgets

$(BUILDDIR)/%.o: %.cpp
      ...

在尝试构建"build/widgets/apple.o"时,make将在VPATH中搜索apple.cpp .请注意,构建规则必须使用特殊变量才能访问实际的文件名查找:

When attempting to build "build/widgets/apple.o", make will search for apple.cpp in VPATH. Note that the build rule has to use special variables in order to access the actual filename make finds:

$(BUILDDIR)/%.o: %.cpp
        $(CC) $< -o $@

其中"$<"扩展到make放置第一个依赖项的路径.

Where "$<" expands to the path where make located the first dependency.

还要注意,这将在build/widgets中构建所有.o文件.如果要在不同目录中构建二进制文件,可以执行类似的操作

Also note that this will build all the .o files in build/widgets. If you want to build the binaries in different directories, you can do something like

build/widgets/%.o: %.cpp
        ....

build/ui/%.o: %.cpp
        ....

build/tests/%.o: %.cpp
        ....

我建议您使用"固定命令序列",以避免重复实际的编译器构建规则:

I would recommend that you use "canned command sequences" in order to avoid repeating the actual compiler build rule:

define cc-command
$(CC) $(CFLAGS) $< -o $@
endef

然后您可以具有多个规则,如下所示:

You can then have multiple rules like this:

build1/foo.o build1/bar.o: %.o: %.cpp
    $(cc-command)

build2/frotz.o build2/fie.o: %.o: %.cpp
    $(cc-command)

这篇关于如何仅使用一个makefile在子目录中生成带有源代码的Makefile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆