Use the preprocessor to convert code into a string
Asked Answered
A

2

1

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.

Apennines answered 26/11, 2010 at 10:23 Comment(3)
doesn't this work? char x[] = "int x = 5;\n printf(\"%i\", x)";Darcie
The goal of what I want to do is to trick VS into syntax highlighting, "intellisensing", etc. the code that is written in the string.Apennines
what are you trying to do? If you're trying to print things to stdout from your GPU I don't think you're on the right track...Botello
I
3

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.

Intramural answered 26/11, 2010 at 10:25 Comment(0)
G
3

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

Gq answered 26/11, 2010 at 12:53 Comment(1)
Thanks for the tip on working with CUDA. However, this question is not about CUDA, it's about abusing the preprocessor.Apennines

© 2022 - 2024 — McMap. All rights reserved.