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

时间:2022-07-22
本文章向大家介绍将资源文件编译成源代码文件,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

目的:简化使用,比如省去了读取配置或者代码中直接大段难以维护的定义。 常用场景: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); 

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