一见

将资源文件编译成源代码文件

目的:简化使用,比如省去了读取配置或者代码中直接大段难以维护的定义。

常用场景:Schema、Lua、SQL等

Linux 自带了资源编译工具 xxd,可将任意文件编译成 c 源代码文件。
常用命令格式:
|xxd -i 源文件 目标文件|
|--|--|

  • CMake应用示例1(将 test.lua 编译为 test.cpp):
# test.lua 编译成 cpp 文件
exec_program(
    xxd
    ${CMAKE_CURRENT_SOURCE_DIR}
    ARGS
    -i test.lua test.cpp
    RETURN_VALUE errcode
)
if (errcode)
    return ()
endif ()
  • CMake应用示例2(将 test.schema 编译为 test_schema.cpp):
# JSON 的 test.schema 编译成 cpp 文件
exec_program(
    xxd
    ${CMAKE_CURRENT_SOURCE_DIR}
    ARGS
    -i test.schema test_schema.cpp
    RETURN_VALUE errcode
)
if (errcode)
    return ()
endif ()

如果没有 xxd,可使用 https://github.com/eyjian/libmooon/blob/master/tools/resource_maker.cpp

代码中如何使用编译后 c 源代码文件?使用以下方式即可:

extern unsigned char test_lua[];
extern unsigned int test_lua_len;
static const std::string test_lua_script((char*)test_lua, test_lua_len);

完全不需要引用头文件,后续即可以二进制字符串方式使用,既简单又便捷。

posted on 2020-07-20 17:22  -见  阅读(420)  评论(0编辑  收藏  举报

导航