C 使用GNU Make在文件目录上迭代
我的项目有一个名为C 使用GNU Make在文件目录上迭代,c,makefile,gnu-make,C,Makefile,Gnu Make,我的项目有一个名为tests/的目录,其中包含任意数量的C源文件,每个文件都是一个独立的程序,用于测试库。对于每个源文件,我想在我的build/目录中创建一个同名的可执行文件 例如,tests/test_init.c将编译为可执行文件build/test_init 当前,我的Makefile代码段如下所示: BUILD_DIR = build TEST_DIR = tests test_sources:= $(TEST_DIR)/*.c test_executables:= $(patsubs
tests/
的目录,其中包含任意数量的C源文件,每个文件都是一个独立的程序,用于测试库。对于每个源文件,我想在我的build/
目录中创建一个同名的可执行文件
例如,tests/test_init.c
将编译为可执行文件build/test_init
当前,我的Makefile代码段如下所示:
BUILD_DIR = build
TEST_DIR = tests
test_sources:= $(TEST_DIR)/*.c
test_executables:= $(patsubst %.c, %, $(test_sources))
.PHONY: tests
tests: $(test_executables)
$(CC) $^ -o $@ -g
但这并没有产生预期的结果。任何帮助都将不胜感激。首先,您需要找到以下来源:
test_sources:= $(wildcard $(TEST_DIR)/*.c)
然后选择可执行文件的正确名称:
test_executables:= $(patsubst $(TEST_DIR)/%.c, $(BUILD_DIR)/%, $(test_sources))
然后,从相应的源构建测试可执行文件:
$(BUILD_DIR)/%: $(TEST_DIR)/%.c
$(CC) $< -o $@ -g
如果您想让Make运行所有这些测试,您可以创建一个虚假的模式规则run\u test%
,但这可以再等一天。首先您需要找到源:
test_sources:= $(wildcard $(TEST_DIR)/*.c)
然后选择可执行文件的正确名称:
test_executables:= $(patsubst $(TEST_DIR)/%.c, $(BUILD_DIR)/%, $(test_sources))
然后,从相应的源构建测试可执行文件:
$(BUILD_DIR)/%: $(TEST_DIR)/%.c
$(CC) $< -o $@ -g
如果你想让Make运行所有这些测试,你可以创建一个虚假的模式规则
run\u test%
,但这可以再等一天。这个Make文件将检测test/*.c
中的所有文件,并提供任务构建测试,运行测试,以及清除测试
all: build_tests
define test_template
build_tests: test/$(1)
run_tests: build_tests run_test_$(1)
test/$(1) : test/$(1).c
$$(CC) $$^ -o $$@
.PHONY : run_test_$(1)
run_test_$(1) : test/$(1)
test/$(1)
endef
clean: clean_tests
clean_tests:
rm -fv $(foreach test, $(tests),test/$(test))
# Auto detect the tests (any .c file in the test directory),
# and store the list of tests names.
tests := $(foreach test, $(wildcard test/*.c),$(patsubst %.c,%,$(notdir $(test))))
# Add information about each test to the Makefile.
$(foreach test, $(tests), $(eval $(call test_template,$(test))))
注意:我不知道如何让标签在markdown中的代码块内工作,因此如果复制并粘贴此标签,则需要在每一缩进行上用单个标签替换空格。此Makefile将检测test/*.c
中的所有文件,并提供任务构建测试,运行测试,以及清除测试
all: build_tests
define test_template
build_tests: test/$(1)
run_tests: build_tests run_test_$(1)
test/$(1) : test/$(1).c
$$(CC) $$^ -o $$@
.PHONY : run_test_$(1)
run_test_$(1) : test/$(1)
test/$(1)
endef
clean: clean_tests
clean_tests:
rm -fv $(foreach test, $(tests),test/$(test))
# Auto detect the tests (any .c file in the test directory),
# and store the list of tests names.
tests := $(foreach test, $(wildcard test/*.c),$(patsubst %.c,%,$(notdir $(test))))
# Add information about each test to the Makefile.
$(foreach test, $(tests), $(eval $(call test_template,$(test))))
注意:我不知道如何在markdown中使制表符在代码块内工作,因此如果复制并粘贴此制表符,则需要在每个缩进行上用单个制表符替换空格