PhoenixBlue
PhoenixBlue

Reputation: 1037

undefine a macro at execution in C

Is it possible to undefine a macro at run time? This is what I tried:

for(int i=2; i<argc; i++){
    if(strcasecmp(argv[i], "+debug")==0){
        puts("+debug");
#ifndef DEBUG
#define DEBUG
#endif
    }
    if(strcasecmp(argv[i], "-debug")==0){
        puts("-debug");
#ifdef DEBUG
#undef DEBUG
#endif
    }

I compiled the code with the macro DEBUG defined. What it does is, it will display all messages on standard output. If not defined, it will not display those messages. So when I run the application with the option -debug, it should undefine the macro. But it did not! I still get messages on console!

Anyone care to help?

Upvotes: 0

Views: 519

Answers (4)

Bodo
Bodo

Reputation: 9875

As others already explained, preprocessor macros are handled ad compile time, you cannot change it at run time.

If you want to switch the debug stuff at run time you need a run time configuration, e.g. a variable. You can use the preprocessor macros to set the default value.

Example using a global variable for the run time switch with a default value based on the preprocessor macro:

#ifdef DEBUG
int debug = 1; /* default is ON */
#else
int debug = 0; /* default is OFF */
#endif

    for(int i=2; i<argc; i++){
        if(strcasecmp(argv[i], "+debug")==0){
            puts("+debug");
            debug = 1; /* change value at run time */
        }
        if(strcasecmp(argv[i], "-debug")==0){
            puts("-debug");
            debug = 0; /* change value at run time */
        }

/* ... */


/* instead of 

#ifdef DEBUG
   do_debug_stuff();
#endif

you would have to use */
   if(debug) {
      do_debug_stuff();
   }

Upvotes: 1

Babajan
Babajan

Reputation: 382

Is it possible to undefine a macro at run time?

Answer is simple : "No way"

How can one expect that to happen.

Infact pre-processor directives are handled even before compilation.

Upvotes: 0

Amadan
Amadan

Reputation: 198466

All preprocessor directives (#...) are executed before the compilation in the preprocessor step, which transforms the original source code into the source code ready for compilation. The resulting (transformed) source code does not contain any preprocessor directives any more. Thus, it is not possible to interact with preprocessor directives short of modifying the original source code and recompiling the program.

Upvotes: 5

Bathsheba
Bathsheba

Reputation: 234855

No you can't. Macros are replaced at the preprocessor stage so never make it into the final program.

Upvotes: 5

Related Questions