c++ - 有没有Makefile依赖的 "watch"/"monitor"/"guard"程序?

标签 c++ build makefile filesystems guard

我最近被 nodemon 宠坏了在终端窗口中,每当我保存更改时运行我的 Node.js 程序。

我想用我的一些 C++ 代码做一些类似的事情。我的实际项目有很多源文件,但是如果我们假设下面的例子,我想在我保存对 sample.dat 的更改时自动运行 makeprogram.cheader.h

test: program sample.dat
    ./program < sample.dat

program: program.c header.h
    gcc program.c -o program

有没有现成的解决方案可以做到这一点?

(无需启动 IDE。我知道很多 IDE 可以在您更改文件时重建项目。)

最佳答案

如果您使用的平台支持 inotifywait (据我所知,只有 Linux;但由于您询问了 Make,看来您很有可能在 Linux 上;对于 OS X,请参阅 this question),您可以这样做:

inotifywait --exclude '.*\.swp|.*\.o|.*~' --event MODIFY -q -m -r . |
while read
do make
done

分解:

inotifywait

监听文件系统事件。

--exclude '.*\.swp|.*\.o|.*~'

排除以 .swp.o~ 结尾的文件(您可能想要添加到此列表)。

--event MODIFY

当您找到一个时,打印出发生事件的文件的文件路径。

-q

不打印启动消息(因此不会过早调用 make)。

-m

持续聆听。

-r .

递归地监听当前目录。然后它被输送到一个简单的循环中,该循环为读取的每一行调用 make。

根据您的需要量身定制。您可能会发现 inotifywait --help 和联机帮助页很有帮助。


这是一个更详细的脚本。我没有对其进行太多测试,因此请谨慎使用。它旨在防止构建在不必要的情况下一次又一次地发生,例如在 Git 中切换分支时。

#!/bin/sh
datestampFormat="%Y%m%d%H%M%S"
lastrun=$(date +$datestampFormat)
inotifywait --exclude '.*\.swp|.*\.o|.*~' \
            --event MODIFY \
            --timefmt $datestampFormat \
            --format %T \
            -q -m -r . |
while read modified; do
    if [ $modified -gt $lastrun ]; then
        make
        lastrun=$(date +$datestampFormat)
    fi
done

关于c++ - 有没有Makefile依赖的 "watch"/"monitor"/"guard"程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12556330/

相关文章:

c++ - 多线程程序和fork() : alternative or safe implementation

c++ - 左值引用和右值引用的区别

linux - 我们如何确定 ffmpeg 所需的依赖项

c++ - 如何让cmake找到CUDA

c - Makefile 不适用于多个 c 文件,但适用于单个 c 文件

c++ - 在按钮背景上拉伸(stretch)/收缩时位图质量下降

c++ - ld : -bind_at_load and -bitcode_bundle (Xcode setting ENABLE_BITCODE=YES) cannot be used together

opencv - 安装 OpenCV 3.0.0-dev,配置选项问题

c++ - 在 makefile 中为 visual studio C++ build 定义宏

makefile - 如何修改安装路径而不再次运行配置脚本/cmake