如何编译目录中的所有.c文件并输出每个没有.c扩展名的二进制文件

我有一个包含多个c源文件的目录(每个文件本身就是一个小程序),我想一次编译所有文件,并在子目录bin /中为每个文件输出二进制文件。 二进制文件的名称应该是c源文件之一,但没有.c扩展名。 我怎么能在Makefile中完成类似的东西?

例:

-src ll.c lo.c -bin ll lo 

我想出的第一件事是:

 CFLAGS=-Wall -g SRC=$(wildcard *.c) all: $(SRC) gcc $(CFLAGS) $(SRC) -o bin/$(SRC) 

但这并不是我认为的那样。

all: $(SRC)告诉make all目标都将每个源文件作为先决条件。

该目标的配方( gcc $(CFLAGS) $(SRC) -o bin/$(SRC) )然后尝试在所有源文件上运行gcc并告诉它创建bin/作为输出( SRC) with the rest of the words from $(SRC)`是gcc的其他额外参数。

你想要更像这样的东西:

 SRCS := $(wildcard *.c) # This is a substitution reference. http://www.gnu.org/software/make/manual/make.html#Substitution-Refs BINS := $(SRCS:%.c=bin/%) CFLAGS=-Wall -g # Tell make that the all target has every binary as a prequisite and tell make that it will not create an `all` file (see http://www.gnu.org/software/make/manual/make.html#Phony-Targets). .PHONY: all all: $(BINS) bin: mkdir $@ # Tell make that the binaries in the current directory are intermediate files so it doesn't need to care about them directly (and can delete them). http://www.gnu.org/software/make/manual/make.html#index-_002eINTERMEDIATE # This keeps make from building the binary in the current directory a second time if you run `make; make`. .INTERMEDIATE: $(notdir $(BINS)) # Tell make that it should delete targets if their recipes error. http://www.gnu.org/software/make/manual/make.html#index-_002eDELETE_005fON_005fERROR .DELETE_ON_ERROR: # This is a static pattern rule to tell make how to handle all the `$(BINS)` files. http://www.gnu.org/software/make/manual/make.html#Static-Pattern $(BINS) : bin/% : % | bin mv $^ $@ 

[我忽略了你说你想在Makefile中做到这一点的地方。 我的解决方案是直壳。]

我会用类似的东西

 CFLAGS=-Wall -g for cfile in *.c do cc $CFLAGS -o bin/`basename $cfile .c` $cfile done 

Make非常聪明,可以使用隐式规则。 确保没有makefile存在并运行:

  for f in *.c; do make CFLAGS='-Wall -g' ${f%.c} && mv ${f%.c} bin; done