macros - Conditional C preprocessor directives -


in code had macro:

#define tps 1(or 0) int main() { ....    if(var)    { #ifdef tps #endif    } } 

but now, want merge if(var) macro acheive:

int var=1; #define tps   (if(var))  int main() {    int a, b, c;    a=1;b=2;c=3; #if tps    printf("a: %d\n", a);    printf("b: %d\n", b);    printf("c: %d\n", c); #endif    printf("++a: %d\n", ++a);    return 0;  } 

i.e. block of code inside macro conditionals should present if var=1 eg, var=1:

int main() {    int a, b, c;    a=1;b=2;c=3;    printf("a: %d\n", a);    printf("b: %d\n", b);    printf("c: %d\n", c);    printf("++a: %d\n", ++a);    return 0;  } 

and, var=0:

int main() {    int a, b, c;    a=1;b=2;c=3;    printf("++a: %d\n", ++a);    return 0;  } 

how can implement #define tps achieve this?

you cannot dreaming of.

preprocessing 1 of earliest phase of compiler (e.g. gcc). , tps looks want have compilation behavior depends on runtime variable var. conceptually, compiler first preprocessing source. can use gcc -c -e preprocessed textual form.

at compilation time, variable has name , compiler find location (but variable not have value during compilation). @ runtime, variable has location containing value. values don't exist @ compilation time, can't use them in preprocessing phase.

however, preprocessing can conditionnal, like

#if wantprint    printf("a: %d\n", a); #endif 

and pass (or not) -dwantprint=1 flag compiler.

you code

int var; int main() {   int a, b, c;   a=1;b=2;c=3;   if (var) {     printf("a: %d\n", a);     printf("b: %d\n", b);     printf("c: %d\n", c);   };   printf("++a: %d\n", ++a);   return 0; } 

btw, perhaps want dynamically load code @ runtime? on linux , posix systems can call dlopen(3) , dlsym. generate c code in (temporary) file, fork process compile shared object, , dlopen shared object, function pointer dlsym call it... see this answer.

fwiw, common lisp has powerful macro system , able "compile" @ runtime, , arbitrary computations @ "compile-time". actually, sbcl may generate machine code while running....


addenda

perhaps want customize behavior of gcc compiler itself. might consider using melt (a domain specific language extend gcc). gcc don't enable customization of preprocessing yet (but of middle-end, working on internal gcc representations gimple)


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -