【问题标题】:Populate an array at compile-time from file在编译时从文件填充数组
【发布时间】:2023-03-23 16:37:01
【问题描述】:

我正在为裸机环境交叉编译一个程序,并且我希望用我存储在文件中的数据填充一个数组。有没有办法在编译时进行读取?

原因:将数据复制粘贴到源中看起来很难看。

【问题讨论】:

  • 您可以编写一个“驱动程序”程序来生成您的源文件。它会从文件中读取数据并将其插入到您的源文件中。
  • 您可以将xxd -iobjcopy 集成到您的构建中。见stackoverflow.com/questions/1155578/…
  • 我不确定,但你可以看看 c++11 中的constexpr

标签: c++ arrays


【解决方案1】:

您的构建过程的一部分可以是运行一个程序,该程序将文件作为输入并生成一个将其定义为数组的 C++ 源文件,例如:

char arrayFromFile[] = {
    0x01, 0x02, 0x99, ...  and so on
};

程序本身可能是您的源代码的一部分。

然后在构建周期的后期编译该程序。例如,您可能有以下makefile 段:

generate: generate.cpp
    g++ -o generate generate.cpp    # build data generator

data.cpp: data.dat
    generate data.dat >data.cpp     # create c file with data

prog: prog.cpp data.cpp
    g++ -o prog prog.cpp data.cpp   # create program from source and data

【讨论】:

    【解决方案2】:

    GCC 和 Clang 都可以用来将任意文件作为静态字符串打包到 .o 中。将它使用的符号名称映射到程序员对该文件的看法最终会有点复杂(特别是如果"physical" and "logical" file paths in the build 不是同一件事),但该过程的核心是demonstrated here 并且,忽略极端情况,归结为:

    gcc ... -Wl,--format=binary -Wl,$FILE1 -Wl,$FILE2 ...
    

    (使用 Bazel 作为构建工具的项目可以直接使用包含 bzl 规则。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多