c - "make target"在 "make clean"之后不工作

标签 c makefile gnu-make

我正在尝试为一个小型 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/

相关文章:

在 C 中将输入字符串与具有整数变量的字符串进行比较?

c++ - 为什么这个 makefile 总是在重新编译?

c++ - 简单的更改导致 make : Error 1

makefile - GNU Make : How to call $(wildcard) within $(eval)

makefile - 在 GNU Make 中强制变量扩展

c++ - Make 使用旧的 Makefile

代码将无法正确运行

c - 如何在struct中使用malloc或new?

c - 有没有办法回到 typedef 枚举的字符串?

使用 Makefile 中的通用目标进行 make 的 Bash 补全