gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:35:17 24 4
gpt4 key购买 nike

我有一个包含多个 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/<first word in $(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 $^ $@

关于c - 如何编译目录中的所有 .c 文件并输出不带 .c 扩展名的每个二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31191857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com