How do I temporarily disable a macro expansion in C/C++?

Viewed 25667

For some reason I need to temporarily disable some macros in a header file and the #undef MACRONAME will make the code compile but it will undef the existing macro.

Is there a way of just disabling it?

I should mention that you do not really know the values of the macros and that I'm looking for a cross compiler solution (should work at least in GCC and MSVC).

6 Answers

There are specific rules for function-like macroses invokation in C/C++ language. The function-like macroses have to be invoked in the following way:

  1. Macros-name
  2. Left parethesis
  3. One token for each argument separated by commas

Each token in this list can be separared from another by whitespaces (i.e. actual whitespaces and commas)


With one trick you "disable preprocessor mechanism" with breaking rules for function-like macro invokation, but be still within a rules of function calling mechanism...

#include <iostream>
using namespace std;

inline const char* WHAT(){return "Hello from function";}

#define WHAT() "Hello from macro"

int main()
{
    cout << (*WHAT)() << "\n"; // use function
    cout << (WHAT)() << "\n";  // use function
    cout << WHAT () << "\n";   // use macro
    
    return 0;
}
Related