在编译时将文本文件导入原始字符串文字

Import text file into raw string literal at compile time

我有一个包含应用程序所需资源的文本文件。该文件包含任意纯文本,而非 带有变量赋值的 C++ 代码。我不想将文本文件与我的应用程序一起发送;我宁愿把它编译进去。所以我尝试了以下方法:

#include <iostream>
#include <string>

int main() {
    std::string test = R"(
#include <textresource.txt>
)";
    std::cerr << test << std::endl;
}

我希望第 6 行中的 #include 在预处理时执行,并替换为资源文件的内容。之后,编译器将看到带有资源数据的原始字符串文字。

但是,输出只是文本 #include <textresource.txt>,周围有换行符。显然, #include 永远不会被执行。 (我使用的是 Visual Studio 2015。)

为什么 #include 没有按预期工作?是否有其他一些语法可以在编译时将文本文件(不是代码)导入变量?

我不确定textresource.txt的内容是什么。但是你可以这样做。

文件textresource.c

#include <string>
static std::string myString {"Very large string content ........ you may be need proper escape character depending on your content."};

文件main.cpp

#include <iostream>
#include <string>
#include "textresource.c"
int main() {
    std::string test = myString;
    std::cerr << test << std::endl;
}

Why doesn't the #include work as expected?

C++ 标准的 2.2 翻译阶段列出了步骤:

  1. The source file is decomposed into preprocessing tokens (2.4)...

(在 2.4 预处理标记下你会发现 string-literals 是一种标记类型)

  1. Preprocessing directives are executed

因此包含文本 "#include..." 的字符串文字被正确标记为字符串文字,而不是任何受制于预处理指令执行的内容。

Is there some other syntax that will import a text file (not code) into a variable at compile time?

不是 C++ 语言本身。你当然可以在你的构建系统中编排它......调用一些 shell 或实用程序来拼接你想要的 C++ 源代码。特定的 C++ 编译器可能会提供非标准设施来促进这一点;您需要查看您感兴趣的编译器的文档。