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

落日映苍穹つ 2023-02-28 05:53 168阅读 0赞

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

常用场景:Schema、Lua、SQL等

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








xxd -i 源文件 目标文件
  • CMake应用示例1(将 test.lua 编译为 test.cpp):

    test.lua 编译成 cpp 文件

    exec_program(

    1. xxd
    2. ${ CMAKE_CURRENT_SOURCE_DIR}
    3. ARGS
    4. -i test.lua test.cpp
    5. RETURN_VALUE errcode

    )
    if (errcode)

    1. return ()

    endif ()

  • CMake应用示例2(将 test.schema 编译为 test_schema.cpp):

    JSON 的 test.schema 编译成 cpp 文件

    exec_program(

    1. xxd
    2. ${ CMAKE_CURRENT_SOURCE_DIR}
    3. ARGS
    4. -i test.schema test_schema.cpp
    5. RETURN_VALUE errcode

    )
    if (errcode)

    1. return ()

    endif ()

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

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

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

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

发表评论

表情:
评论列表 (有 0 条评论,168人围观)

还没有评论,来说两句吧...

相关阅读