我正在尝试为小型 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 链接到测试程序。$\
我的问题是,这只有在我先使用make all然后再使用make test时才有效。当我make clean之后是make test。我收到以下错误。
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
cc 调用似乎与作为源的目标文件有误?我很陌生,无法弄清楚这一点。请帮忙。