如何将文本文件编译为 C++ 程序作为常量字符串?

Dan*_*ury 3 c++ gcc clang

I have a C++ program which I'd like to have output a certain text file at some point. Of course I could have it open, read, and output the text file, but then I have to keep the binary and the text file in sync and located together. I'd rather just compile the file in as a string in some part of my build process.

I've seen things like this done as parts of various IDEs. However I'm building from the command line with gcc or clang.

Of course I could just write my own script that produces a temporary .cpp file at compile time and make that a build step in my Makefile, but I was wondering if there was a more established option for doing this.

I would prefer not to take on a lot of other dependencies just to do this.

eer*_*ika 5

有一个建议添加std::embedp1040r4。它的目的是提供几乎这个功能。

在该提案被标准化并实施之前,您将不得不要么

  1. 从输入文件生成源文件。为此存在工具。xxd例如。

  2. 从输入生成目标文件。一个通用工具:objcopy.

  3. 用汇编程序注入:.incbin

源方法是最便携的。


请注意,嵌入不一定是最佳选择。使用非嵌入的单独文件通常是有利的,因为它可以轻松修改输入文件,而无需重新构建可执行文件。让用户传递文件路径以便他们可以替换自己的路径甚至可能是值得的。我的观点是,你会用一种便利来交换另一种便利。