使用preprocessor至code转换为字符串 [英] Use the preprocessor to convert code into a string

查看:94
本文介绍了使用preprocessor至code转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:我不是一个 C 编程

Disclaimer: I am not a C programmer.

我最近看到一个朋友的项目。由于原因,我不明白,他这是在运行时编译一个字符串写入code。这导致这样的:

I have recently seen a friend's project. Due to reasons I don't understand, he writes code in a string which is compiled at runtime. This results in something like:

char x[] = "int y = 5; printf(\"%i\", y)";
run_this_code(x);

这是可怕的使用,因为Visual Studio的不退一步,做语法高亮等。

Which is horrible to use because Visual Studio doesn't step in and do syntax highlighting etc.

使用一些preprocessor滥用,这是可以做到的伎俩的Visual Studio以为你在写现实code,然后具有preprocessor把它变成一个字符串编译器之前得到的保持你的资源。这工作:

Using some preprocessor abuse, it is possible to do trick Visual Studio into thinking you're writing real code and then having the preprocessor turn it into a string before the compiler gets hold of your source. This works:

#define STRINGIFY(x) #x

int main(void){
        char[] y = STRINGIFY(
                int x = 5;
                printf("%i", x);
        );
        printf("%s", y);
}

这样做的问题是它打印出:

The problem with this is it prints out:

int x = 5; printf("%i\n", x);

问题则是运行时编译器说第1行的错误有没有使它包括新行的一种方式?

The problem then is the runtime compiler says Error on line 1. Is there a way of making it include the newlines?

更新这是不是我的问题。这是别人的code,我刚刚成为兴趣使用preprocessor,使他的生活更轻松的想法。我不知道为什么他这样做是这样的。

Update This is not my problem. It is someone else's code, I just became interested in the idea of using the preprocessor to make his life easier. I have no idea why he's doing it like this.

更新 CUDA删除所有提及,因为这问题是关于preprocessor,不CUDA。

Update removed all mention of CUDA because this question is about the preprocessor, not CUDA.

推荐答案

我首先建议刚逃脱换行符应该够了。有过时间来验证(并看到了问题的所有者评论),我认识到,不剪。

I first suggested that just escaping the newlines should be enough. Having had time to verify (and seeing the comment by the question's owner), I realize that doesn't cut it.

我做了一些测试,并明确投入换行符符号似乎工作:

I did some testing, and explicitly putting in newline symbols seems to work:

char[] y = STRINGIFY(
                int x = 5;\n
                printf("%i", x);\n
        );

我只测试了这个在Linux上虽然不是一个语法感知的IDE。这有可能是那些裸看新行会,而不是得到标记为语法错误,由一个聪明的语法高亮显示。

I have only tested this on Linux though, not in a syntax-aware IDE. It's possible that those "bare-looking" newlines will instead get flagged as syntax errors, by a clever syntax highlighter.

这篇关于使用preprocessor至code转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆