有没有办法为 c++ 制作一个 makefile,每次使用 make 命令时都会运行该程序?

Is there a way to make a makefile for c++ that will run the program every time you use the make command?

本文关键字:make 命令 程序 运行 c++ 一个 makefile 有没有      更新时间:2023-10-16

我有一个C++项目的makefile,它编译并创建该程序的可执行文件,然后运行该可执行文件。问题是,我希望每次使用 make 命令时都运行可执行文件,但如果对源代码没有需要重新编译的更改,make 将返回"make:无事可做"。有没有办法格式化makefile,以便在需要编译时编译并运行,否则只需运行可执行文件?

您可以简单地添加一个新目标来运行程序,并使该目标依赖于程序的创建。如果将该目标设置为默认目标 (all:( 的依赖项,它将始终在成功构建后运行程序。

喜欢这个:

SOURCES = ./src/main.cpp

OBJECTS = ./bin/main.o

# default target to build hello executable & run it if successful
all: hello run
hello: $(OBJECTS)
$(CXX) -o $@ $^
bin/%.o : src/%.cpp
$(CXX) -c $(CPPFLAGS) $(CXXFLAGS) -o $@ $< $(LDFLAGS)
run: hello
./hello
clean:
@rm -rf hello $(OBJECTS)
.PHONY: all run clean

注意:目标名称"run"没有什么特别之处。我本可以称之为"wibble"。