1
#include <stdio.h>
#define DEBUG

#ifdef DEBUG
#define MAGIC 5
#endif

int main(void){
        printf("\n magic is %d",MAGIC);
        return 0;
    }

Now i want to undef DEBUG so this program should give compilation error

gcc test.c -U DEBUG

But it does not give any error and works fine. It means -U does not work.

so how can I undef any name at compile time in gcc?

Marco A.
  • 43,032
  • 26
  • 132
  • 246
Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222

4 Answers4

2

man GCC says,

 -D and -U options are processed in the order they are given on the command line.

Seems you cannot undefine a MACRO from CLI which is defined in program.

Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46
2
#include <stdio.h>

#define DEBUG

// add some new lines
#if defined(CUD_DEBUG) && defined(DEBUG)
#undef DEBUG
#endif

#ifdef DEBUG
#define MAGIC 5
#endif

int main(void)
{
    printf("\n magic is %d", MAGIC);
    return 0;
}

To compile that by command:

gcc test.cc -DCUD_DEBUG

CUD_DEBUG means compiler undefine debug.

Alex Chi
  • 726
  • 6
  • 10
0

You should write your code like this

#include <stdio.h>
//#define DEBUG

#ifdef DEBUG
#define MAGIC 5
#else
#define MAGIC 1
#endif

int main(void){
        printf("\n magic is %d",MAGIC);
        return 0;
    }

Now gcc test.c -U DEBUG will work

Rahul R Dhobi
  • 5,668
  • 1
  • 29
  • 38
  • 1
    see my source has defined that macro and i want to undef it by command line. If you comment out its definition in source code then there is no need to use -U at CLI. – Jeegar Patel Feb 05 '14 at 11:40
  • 2
    @Mr.32: You do not need to define DEBUG macro explicitly – Rahul R Dhobi Feb 05 '14 at 11:47
  • i know and i am not doing that. i am not sure it is defined in source or any header file so i just want to make sure about its undef so i want to undef it at CLI. so my question is if by chance in any header file if it is defined then can it be undef using CLI? I have written just sample code to explain my problem – Jeegar Patel Feb 05 '14 at 11:56
0

Don't define DEBUG inside the program. Instead, define DEBUG while compilation as gcc test.c -DDEBUG.

If you want to get an error at compile time then don't define DEBUG at compile time as gcc test.c:

test.c: In function "main":
test.c:8: error: "MAGIC" undeclared (first use in this function)
test.c:8: error: (Each undeclared identifier is reported only once
test.c:8: error: for each function it appears in.)
John_West
  • 2,239
  • 4
  • 24
  • 44
MRaja
  • 1