Use the preprocessor to convert code into a string

风流意气都作罢 提交于 2019-12-11 04:55:20

问题


Disclaimer: I am not a C programmer.

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);

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

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);

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

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.

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


回答1:


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
        );

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.




回答2:


When coding in CUDA, you have to send all the code to the graphics card in a string to be compiled.

What makes you say this? Take a look at the CUDA SDK examples, you can put the CUDA code into .cu files which are then compiled using nvcc. You can have syntax highlighting, intellisense and all the Visual Studio goodness! See the CUDA Programming Guide and this post for more information



来源:https://stackoverflow.com/questions/4284403/use-the-preprocessor-to-convert-code-into-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!