Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top