How do I at compile time undefine a compiler macro using gcc. I tried some compile args to gcc like -D but I can't get to see the "not defined" message.
Thanks
#include <iostream>
#define MYDEF
int main(){
#ifdef MYDEF
std::cout<<"defined\n";
#else
std::cout<<"not defined\n";
#endif
}
You can use the -U option with gcc, but it won't undefine a macro defined in your source code. As far as I know, there's no way to do that.
You can resort to filtering source code and give this back to gcc for compilation, like this pseudo code:
Hope it helps.
You should wrap the
MYDEF
definition in a preprocessor macro, the presence of which (defined on the command line) would then prevent MYDEF from being defined. A bit convoluted to be sure but you can then control the build in the way you want from the command line (or Makefile). Example:Then from the command line when you don't want MYDEF:
gcc -DDONT_DEFINE_MYDEF ...
The code use case is not right. As I see, you have hard coded
#define
in the file. If compiler initially assumesMYDEF
undefined, it will define it once it start processing the file.You should remove the line
#define MYDEF
. And I hope your test case will work, if you passMYDEF
to-D
and-U
.http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Preprocessor-Options.html#Preprocessor-Options
The
-U
options seemed like what you could have needed... but then again you can't override a definition contained in your source code without resorting to more preprocessor directives.Here is one possibility that doesn't completely cover your use case but which I found to be helpful in my case.
If your
MYDEF
were #defined in a separate header file #included from the .c file you could force the definition of the #include guard macro with the-D
option (thus preventing theMYDEF
#definition) then either actively #define (still with the-D
option)MYDEF
to something else or just leave it undefined.It is clear that anything else defined in the header file would also be missing but this was for me a solution to forcedly undefine a macro without changing the third-party code.