c++ - 将二进制数据文件包含到编译的二进制文件中,而不转换为十六进制数组

标签 c++ c gcc

我经常希望将外部文件中的二进制数据包含(编译)为 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++ :

  1. 数据文件data.dat :

    ABC
    
  2. 转换为目标文件:

    ld -r -b binary data.dat -o data.o
    

    如上所述here ,与 -b binary <name>选项目标文件将包含文件 <name> 中的原始二进制数据在 .data部分和三个符号_binary_<name>_start , _binary_<name>_end ,和_binary_<name>_size将被创建。

  3. 简单的程序:

    #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 << ' ';
    }
    
  4. 编译和链接:

    g++ -c test.cpp
    g++ test.o data.o
    
  5. 输出:

    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/

相关文章:

c++ - gRPC C++,客户端 : "14: Connect Failed"

C++如何使用相同的函数两次使用不同的名称和变量的不同名称

c++ - 类内枚举前向声明是否可能?

c - getChar()从C中的段落中删除单词

C - scanf 无符号字符

c++ - GCC相当于VC的浮点模型切换?

php - MemCache-repcached编译错误

c++ - 是否可以用 C++ 而不是 C 来编写 OpenCL 内核?

c - 字符串、获取和执行

c++ - gcc4mbed 编译器问题 (c++)