我正在尝试为一个小型 C 程序编写 Makefile。它的结构是
项目根
- src(源文件)
- 测试(测试文件)
- 构建(二进制程序)
我的 make 文件在下面。
CFLAGS = -g -Wall -Isrc $(OPTFLAGS)
LDLIBS = $(OPTLIBS)
PREFIX ?= /usr/local/
OPTVALGRIND="valgrind --track-origins=yes --log-file=tests/valgrind.log"
TARGET_SRC = src/hello_make.c
TARGET = build/hello_make
SOURCES := $(wildcard src/*.c)
SOURCES := $(filter-out $(TARGET_SRC),$(SOURCES))
OBJECTS = $(patsubst %.c,%.o,$(SOURCES))
TEST_SRC = $(wildcard tests/*_tests.c)
TESTS = $(patsubst %.c,%,$(TEST_SRC))
TEST_FILE ?= hello_make_tests
all: $(TARGET) tests
$(TARGET): build $(OBJECTS)
$(CC) $(CFLAGS) $(TARGET_SRC) $(OBJECTS) $(LDLIBS) -o $@
.PHONY: compile_tests tests test testv valgrind build clean
compile_tests: LDLIBS += -lrt -lm
compile_tests: CFLAGS += $(OBJECTS)
compile_tests: build $(OBJECTS) $(TESTS)
@echo "TARGET=$(TARGET), TESTS=$(TESTS)"
@echo "compile_tests done"
tests: compile_tests
sh ./tests/run_tests.sh
test: compile_tests
sh ./tests/run_test.sh tests/$(TEST_FILE)
testv: compile_tests
sh ./tests/run_test.sh tests/$(TEST_FILE)
valgrind:
VALGRIND=$(OPTVALGRIND) $(MAKE) -s
clean:
rm -rf $(OBJECTS)
rm -rf $(TARGET)
rm -rf $(TESTS)
rm -rf build
rm -rf tests/*.log
build:
@mkdir -p build
我有一个目标测试和 testv(对应于使用 valgrind 运行)。 所以当我这样做的时候,
make test TEST_FILE=hello_make_tests
它应该构建此测试所需的任何内容。然后运行测试/hello_make_tests。
我的大部分 Makefile 都在工作。它构建源文件并将其编译为 .o 将它们链接到测试程序。 $\
My problem is that this only works if I use make all first then followed by make test. When I do make clean followed by make test. I get the following error.
cc -g -Wall -Isrc src/get_one.o src/get_three.o src/get_two.o -c -o src/get_one.o src/get_one.c
cc: error: src/get_one.o: No such file or directory
cc: error: src/get_three.o: No such file or directory
cc: error: src/get_two.o: No such file or directory
make: *** [src/get_one.o] Error 1
The cc call seems to be wrong with object files acting as sources? I am pretty new to make and am unable to figure this out. Please help.
最佳答案
这一行
compile_tests: CFLAGS += $(OBJECTS)
将所有对象添加到 CFLAGS 变量中,编译时将由隐式规则(内置于 make 中)使用。
尽量在您的 makefile 中将源代码、编译器标志和生成的目标文件分开,以避免这种混淆。
如果您不确定它们的用法,请快速查看 makefile 标志的文档。
关于c - "make target"在 "make clean"之后不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12896665/