makefile: 没有创建目标 '%.o' 的规则

makefile: No rule to make target '%.o'

我有 3 个文件:Source.cpp 2ndfile.cpp 2ndfile.hpp 我正在尝试用 mingw32-make

编译它们

makefile 不起作用:

all: launch.exe

launch.exe: %.o
    g++ -o $@ $^

%.o: %.cpp
    g++ -c $< -std=gnu++11

有效的 makefile:

all: launch.exe

launch.exe: source.o 2ndfile.o
    g++ -o $@ $^

source.o: source.cpp
    g++ -c source.cpp -std=gnu++11

2ndfile.o: 2ndfile.cpp
    g++ -c 2ndfile.cpp -std=gnu++11

我的问题是:为什么第一个不起作用? '%' 模式有什么问题? 我得到的错误:mingw32-make: *** No rule to make target '%.o', needed by 'launch.exe'. Stop.

My question is: why the first one doesn't work? What's my problem with '%' patterns?

模式规则通过名称中的公共元素将目标与先决条件匹配,由 % 通配符表示。你以这个规则的形式展示你自己的例子:

%.o: %.cpp
    g++ -c $< -std=gnu++11

另一方面,这条规则...

launch.exe: %.o
    g++ -o $@ $^

... 不是 模式规则,因为目标名称不包含 %。在那里,您似乎试图以完全不同的方式使用 % ,类似于 glob 模式中的 * 。它没有达到那个目的,即使在模式规则中也是如此。这会给模式规则一个非常不同(而且用处不大)的含义。相反,在您的非模式规则中, % 被视为普通字符。

编写 makefile 的方法有很多种,但是探索模式规则的一个好的、简单的模型应该是第一个和第二个示例的组合:

all: launch.exe

launch.exe: source.o 2ndfile.o
    g++ -o $@ $^

%.o: %.cpp
    g++ -c $< -std=gnu++11

将 % 替换为 *.

all: launch.exe

launch.exe: *.o
    g++ -o $@ $^

*.o: *.cpp
    g++ -c $^ -std=gnu++11

编辑:下面有一个为什么这是个坏主意的答案。这是有效的:

all: launch.exe

launch.exe: Source.o 2ndfile.o
    g++ -o $@ $^

%.o: %.cpp
    g++ -c $^ -std=gnu++11