常用场景: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,可使用 。
代码中如何使用编译后 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);
完全不需要引用头文件,后续即可以二进制字符串方式使用,既简单又便捷。