C/C++,您可以将文件#include到字符串文字中吗?

Jos*_*vin 41 c c++ include string-literals c-preprocessor

我有一个C++源文件和一个Python源文件.我希望C++源文件能够将Python源文件的内容用作大字符串文字.我可以这样做:

char* python_code = "
#include "script.py"
"
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为每条线的末尾都需要.我可以手动复制并粘贴Python代码的内容,并用引号和终止\n包围每一行,但这很难看.即使python源有效地编译到我的C++应用程序中,我也希望将它保存在一个单独的文件中,因为它更有条理,并且对编辑器更有效(emacs不够聪明,无法识别C字符串文字是python代码,当你在里面时切换到python模式).

请不要建议我使用PyRun_File,这是我首先要避免的;)

bdo*_*lan 36

C/C++预处理器以令牌为单位,字符串文字是单个令牌.因此,你不能干预像这样的字符串文字的中间.

您可以将script.py预处理为:

"some code\n"
"some more code that will be appended\n"
Run Code Online (Sandbox Code Playgroud)

和#include,但是.或者您可以使用生成准备包含的C静态数组.xxd? -i

  • +1代表xxd.该脚本可能并不一定需要是字符串文字. (12认同)

Mic*_*hop 10

这不会让你一直到那里,但它会让你非常接近.

假设script.py包含这个:

print "The current CPU time in seconds is: ", time.clock()
Run Code Online (Sandbox Code Playgroud)

首先,将它包装起来:

STRINGIFY(print "The current CPU time in seconds is: ", time.clock())
Run Code Online (Sandbox Code Playgroud)

然后,在您包含它之前,执行以下操作:

#define STRINGIFY(x) #x

const char * script_py =
#include "script.py"
;
Run Code Online (Sandbox Code Playgroud)

可能还有比这更紧凑的答案,但我还在寻找.