【问题标题】:Makefile: checking existence of filesMakefile:检查文件是否存在
【发布时间】:2013-03-10 14:48:53
【问题描述】:

我正在制作一个使用 c 源文件和头文件的 makefile。

我想在编译之前检查所有这些文件是否存在,以便如果缺少一个,打印一条自定义消息而不是通常的“没有规则来制作目标”。

代码如下:

PROG1=file1
PROG2=file2
INCLUDE=header
all: $(PROG1).x $(PROG2).x
%.x : %.c $(INCLUDE).c
     $(CC) -o $/$@ $^
     @ echo File $@ has been successfully created from $^;

我应该在哪里以及如何检查 file1.c、file2.c 和 header.h 是否存在,以便在其中任何一个缺失时打印自定义错误消息?

【问题讨论】:

    标签: bash makefile


    【解决方案1】:
    PROG1=file1
    PROG2=file2
    INCLUDE=header
    
    all: $(PROG1).x $(PROG2).x
    
    %.x : %.c $(INCLUDE).c
        $(CC) -o $/$@ $^
        @echo File $@ has been successfully created from $^
    
    %.c :
        @echo Missing $@
    
    %.h :
        @echo Missing $@
    

    这行得通吗?如果这些文件不存在,您将得到类似以下输出:

    posey@DEATHSTAR:~$ make all
    Missing file1.c
    Missing header.c
    cc -o file1.x file1.c header.c
    cc: error: file1.c: No such file or directory
    cc: error: header.c: No such file or directory
    cc: fatal error: no input files
    compilation terminated.
    make: *** [file1.x] Error 4
    

    【讨论】:

    • 发挥了魅力!这种方式比我尝试的方式要容易得多。
    猜你喜欢
    • 2010-09-19
    • 2016-02-10
    • 2019-09-02
    • 2011-08-02
    • 2011-07-30
    • 2012-01-10
    • 2021-12-25
    相关资源
    最近更新 更多