首页 > 解决方案 > 使用 SCons 动态重新创建包含文件

问题描述

我需要修复一个 SCons 项目,其中包含文件由 SCons 动态生成。我创建了一个简单的例子来说明这个问题。SConstruct看起来像这样:

current_time = Command("current_time.h",
                       None,
                       "echo '#define CURRENT_TIME' `date +%H%M` > $TARGET")
test = Program("test", "test.cpp", current_time)
# AlwaysBuild(current_time)

test.cpp

include <iostream>
#include "current_time.h"
int main() {
    std::cout << "the time is: " << CURRENT_TIME << std::endl;
}

当时间改变时,SCons 不会重建项目,因为它不是魔法。解决它的一种方法是添加AlwaysBuild(current_time)到 SCons 文件中。

在实际项目中,重建包含文件AlwaysBuild是相当昂贵的,而且它只需要每天重建一次,因为没有时间而是日期会改变。那么,我怎样才能实现文件每天只重新生成一次呢?

解决方案:我创建了一个返回生成的包含文件内容的函数:

def include_file_contents():
    ...
    return file_contents  # str

然后我在依赖项中替换None为:Value(include_file_contents())

    current_time = Command("current_time.h",
                       Value(include_file_contents()),
                       "echo '#define CURRENT_TIME' `date +%H%M` > $TARGET")

标签: pythonscons

解决方案


像这样的东西应该工作:

import time
now=time.strftime("%H:%M",time.localtime())
current_time = Command("current_time.h",
                       Value(now),
                       "echo '#define CURRENT_TIME' %s > $TARGET"%now)
test = Program("test", "test.cpp") 

您不必将 current_time.h 作为来源。SCons 将扫描 test.cpp 并找到包含的文件。


推荐阅读