使用makefile将时间戳插入可执行文件名

use*_*827 4 c++ makefile

我有一个简单的make文件,我想将当前日期和时间插入它创建的可执行文件中.

类似于:NOW=$(date +"%c")附加到exe名称.最好的方法是什么?

谢谢!

Bar*_*ski 7

我想你已经Makefile创建了一个应用程序.所以这是你可以添加的东西:

# Use ':=' instead of '=' to avoid multiple evaluation of NOW.
# Substitute problematic characters with underscore using tr,
#   make doesn't like spaces and ':' in filenames.
NOW := $(shell date +"%c" | tr ' :' '__')

# Main target - your app + "date"
all: foo_$(NOW)

# Normal taget for your app which already have.
foo: foo.cpp

# Copy "normal" app to app_DATE
# You'll rater want copy then move, otherwise make will have
#   to link your app again during each execution (unless that's
#   exactly what you want).
foo_$(NOW): foo
    cp $^ $@
Run Code Online (Sandbox Code Playgroud)

注意替换':''_'.如此处所示,如果日期包含冒号make,则可能无法解析Makefile.

我目前无法访问Mac OS X,所以这只是在Ubuntu上测试过,但我曾经在Mac机器上工作一次而且我没有发现任何显着的差异make.所以它也适合你.

---编辑---

正如Beta正确评论的那样,上述方法每次make调用时都会创建具有当前日期的新副本.有时候可能会有所需要,所以我会留下它,并建议在情况不同的情况下采用以下方案:

# Same as above...
NOW := $(shell date +"%c" | tr ' :' '__')

# Default target
all: foo  # <-- not foo_$(NOW) anymore, foo_$(NOW) target is removed altogether

OBJ := foo.o bar.o  # other ...

# Normal taget for your app which already have, but...
foo: $(OBJ)
    $(CXX) $(LDFLAGS) $^ -o $@
    cp $@ $@_$(NOW)  # <-- additional copy at the end (read on below)
Run Code Online (Sandbox Code Playgroud)

为什么foo_$(NOW)目标消失了?因为你需要创建应用程序的日期stampped副本,如果你修改应用程序本身.这意味着您无法创建目标,因为make这样总会创建副本(如上面的方案).

然而,这意味着make不知道副本的存在.副本不存在于make启动时创建的依赖关系图中.因此,副本不能用作任何其他目标的先决条件.这不是一个缺点,但直接的结果是,如果我们要创建副本,我们不会提前知道.(如果某人有办法克服这个问题而不进行二次运行,请放纵我:)).