问题描述
我有一个包含多个c源文件的目录(每个文件本身就是一个小程序),我想一次编译所有源文件,并在子目录bin/中输出每个二进制文件的二进制文件.二进制文件的名称应为c源文件之一,但不带.c扩展名.我该如何在Makefile中完成类似的操作?
I have a directory with multiple c source files (every file is a small program by itself) which I would like to compile all at once and output the binary for each one in the subdirectory bin/. The name of the binary should be the one of the c source file, but without the .c extension.How could I accomplish something like that in a Makefile?
示例:
-src
ll.c
lo.c
-bin
ll
lo
我想到的第一件事是:
CFLAGS=-Wall -g
SRC=$(wildcard *.c)
all: $(SRC)
gcc $(CFLAGS) $(SRC) -o bin/$(SRC)
但这并不能像我想的那样有效.
But this does not really work how I thought it would.
推荐答案
all: $(SRC)
行告诉我们all
目标具有 every 源文件作为前提.
The line all: $(SRC)
tells make that the all
target has every source file as a prerequisite.
该目标(gcc $(CFLAGS) $(SRC) -o bin/$(SRC)
)的配方然后尝试在 all 源文件上运行gcc,并告诉其创建bin/<first word in
$(SRC)with the rest of the words from
$( SRC)`是gcc的其他参数.
The recipe for that target (gcc $(CFLAGS) $(SRC) -o bin/$(SRC)
) then tries to run gcc on all the source files and tells it to create as output the bin/<first word in
$(SRC)with the rest of the words from
$(SRC)` being other, extra, arguments to gcc.
您想要更多类似这样的东西:
You want something more like this:
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 $^ $@
这篇关于如何编译目录中的所有.c文件并输出每个不带.c扩展名的二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!