强制生成文件生成源两次

force makefile to build sources twice

本文关键字:两次 文件      更新时间:2023-10-16

我有以下制作文件:

all: a.out b.out
.PHONY: gen_hdr1
gen_hdr1:
    #call script 1 that generates x.h
    rm a.o #try to force rebuild of a.cpp
.PHONY: gen_hdr2
gen_hdr2:
    #call script 2 that generates x.h
    rm a.o #try to force rebuild of a.cpp
b.out: gen_hdr2 a.o
    g++ -o b.out a.o
a.out: gen_hdr1 a.o
    g++ -o a.out a.o
*.o : *.cpp
    g++ -c $< -o $@

A.cpp包括X X.H

我想做什么:

  1. 删除 a.o(如果存在)
  2. 为应用 A 生成 x.h
  3. 编译 A.cpp
  4. 构建应用 A
  5. 删除 a.o(如果存在)
  6. 为应用 B 生成 x.h
  7. 再次编译 A.cpp
  8. 构建应用 B

运行生成文件的输出为:

#call script 1 that generates x.h
rm -f a.o #try to force rebuild of a.cpp
g++    -c -o a.o a.cpp
g++ -o a.out a.o
#call script 2 that generates x.h
rm -f a.o #try to force rebuild of a.cpp
g++ -o b.out a.o
g++: a.o: No such file or directory
g++: no input files
make: *** [b.out] Error 1

基本上,构建应用程序 B 时找不到 a.o。如何强制制作系统重建它?

对于

此类问题,很好的解决方案是使用单独的构建对象文件夹,每个目标多一个子文件夹。

因此,您将得到类似以下内容:

build/first/a.o: src/a.cpp gen/a.h
    # Do you stuff in here
gen/a.h:
    # Generate you .h file if needed
build/second/a.o: src/a.cpp gen/a.h
    # Same thing

使用此解决方案,您将在构建文件夹中拥有所有构建对象,因此 clean 命令稍微简单一些:

clean:
    rm -rf build/*
    rm -rf gen/*
    rm -rf bin/*

您唯一应该确保的是目录在构建之前就存在,但这不是要做的工作:)

如果你必须生成两个版本的a.h,你可以使用相同的设计(gen/first和gen/second文件夹)。

希望对您有所帮助,如果我错过了什么,请告诉我