Makefile pattern rule fails?

别来无恙 提交于 2019-12-04 02:35:40

Make only uses a pattern rule as a sort of fallback. For example:

$ ls
Makefile
$ cat Makefile
%.o: %.c
    gcc $< -o $@
$ make
make: *** No targets.  Stop.

This is fine. Make does not consider the pattern rule as you have not asked it to make anything, and there is no default target in the makefile. Let's ask it to make something that might use the pattern rule.

$ make 1.o
make: *** No rule to make target `1.o'.  Stop.

Expected. 1.c does not exist, so the pattern rule is not considered. Let's try again.

$ touch 1.c
$ make 1.o
gcc 1.c -o 1.o

(and then some error about main being missing).

Personally I dislike these fallback rules intensely. I much prefer listing the targets explicitly. Something like

file.o file2.o f.o: %.o: %.c
    ...

gives you a Target Specific Pattern Rule. These are quite different (see the manual). [Oh, and the pattern gives you no advantage in this noddy example.]

You might need spaces around the : in the first line of your rule. Also, gcc does not take a colon before the output file name; just use -o $@.

Just ran through this problem.

If this is your rule:

%.o:%.c
    gcc $< -o:$@

Make sure that you have a tab and not spaces on the second line before the gcc. Took me a couple of hours to figure out. Also no ':' after the -o flag, as somebody else pointed out.

Are you sure the .c file exists? I think using -d as suggested earlier should help debug this.

If you put only this in a Makefile and call make:

%.o: %.cpp
  g++ -g -o $@ -c $<

It tells: make: *** No targets. Stop.

Because it's not a target. It's a rule.

It will work if your another target needs a .o file.

main.exe: main.o add.o
  g++ -g -o $@ $^

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