C / C ++,你可以#包括文件到一个字符串? [英] C/C++, can you #include a file into a string literal?
问题描述
我有一个C ++源文件和一个Python源文件。我想在C ++源文件,以便能够使用Python源文件中的内容作为一个大的字符串。我可以做这样的事情:
I have a C++ source file and a Python source file. I'd like the C++ source file to be able to use the contents of the Python source file as a big string literal. I could do something like this:
char* python_code = "
#include "script.py"
"
但是,这是行不通的,因为我们需要有\\的每一行的末尾。我可以手动复制和在Python code的内容粘贴,并用引号括和终止\\ n每行,但是这是丑陋的。即使Python源是要有效地编入我的C ++应用程序,我想保持它在一个单独的文件,因为它更有组织和编辑工作得更好(Emacs是没有足够的智慧认识到, ç字符串是蟒蛇code和,而你在里面切换到蟒蛇模式)。
But that won't work because there need to be \'s at the end of each line. I could manually copy and paste in the contents of the Python code and surround each line with quotes and a terminating \n, but that's ugly. Even though the python source is going to effectively be compiled into my C++ app, I'd like to keep it in a separate file because it's more organized and works better with editors (emacs isn't smart enough to recognize that a C string literal is python code and switch to python mode while you're inside it).
请不要建议我用PyRun_File,这就是我试图避免在首位;)
Please don't suggest I use PyRun_File, that's what I'm trying to avoid in the first place ;)
推荐答案
的C / C ++ preprocessor行为在令牌单位,一个字串是的单的标记。因此,你不能在一个字符串一样,中间的干预。
The C/C++ preprocessor acts in units of tokens, and a string literal is a single token. As such, you can't intervene in the middle of a string literal like that.
您可以preprocess script.py成类似:
You could preprocess script.py into something like:
"some code\n"
"some more code that will be appended\n"
和的#include的,但是。或者你可以使用 XXD
-i
来生成一个C静态数组准备列入。
and #include that, however. Or you can use xxd
-i
to generate a C static array ready for inclusion.
这篇关于C / C ++,你可以#包括文件到一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!