我经常希望将外部文件中的二进制数据包含(编译)为 uint8_t
数组到我的程序中(嵌入式或裸机)。
有没有一种方法无需将它们转换为十六进制数组的额外步骤? 因为这涉及额外的构建步骤,有时这些步骤并不容易集成,例如对于 Arduino 工具链。手动执行此操作总是会导致忘记十六进制更新:-)
通常我使用 gcc。因此,如果它是特定于 gcc 的编译指示或其他扩展,我也会很高兴(尽管不像通用解决方案那么高兴)。
也许是这样的
static const __attribute__((rawDataFromFile("myDataFile.bin"))) uint8_t s_data[];
而不是传统的外部方式
bin2hex myDataFile.bin myDataFile.hex
和
static const uint8_t s_data[] = {
#include "myDataFile.hex"
};
适用于 C
的解决方案并在 C++
是首选,但也欢迎仅适用于两者之一的建议。
最佳答案
我想到了一个老技巧,大约 20 年前我在 Turbo Pascal 中使用过,即将二进制文件转换为对象文件。 Here it is with C++ :
数据文件
data.dat
:ABC
转换为目标文件:
ld -r -b binary data.dat -o data.o
如上所述here ,与
-b binary <name>
选项目标文件将包含文件<name>
中的原始二进制数据在.data
部分和三个符号_binary_<name>_start
,_binary_<name>_end
,和_binary_<name>_size
将被创建。简单的程序:
#include <cstdint> #include <iostream> extern const std::uint8_t _binary_data_dat_start[]; extern const std::uint8_t _binary_data_dat_end[]; int main() { for (auto d = _binary_data_dat_start; d != _binary_data_dat_end; ++d) std::cout << (char)*d << ' '; }
编译和链接:
g++ -c test.cpp g++ test.o data.o
输出:
A B C
编辑 1
that also introduces external preprocessing of the data and even introduces the need to know how the symbols will be named
不幸的是,这是事实。您可能想查看this library ,它使用内联汇编来嵌入二进制数据。
编辑2 找到了可能的duplicate question .
关于c++ - 将二进制数据文件包含到编译的二进制文件中,而不转换为十六进制数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58815959/