Using a macro in another macro and then undefining(#undef) the first macro c++

Viewed 321

The following code does not compile:

#define SOME_MACRO(x,y) x+y
#define ADD_ONE_TO(x) SOME_MACRO(x,1)
#undef SOME_MACRO

int main(){
    ADD_ONE_TO(1);
}

Is there any hack to either:

  1. Prevent code duplication by having common functionality in SOME_MACRO and using it in other macros BUT undef`ing it to prevent its usage in common user-code.
  2. Somehow making it so the ADD_ONE_TO macro just copy-pastes the macros it uses instead of referncing them.
  3. Preventing user-code from accessing and using SOME_MACRO but allowing it to be used in other specific parts of code(other, select, macros)
  4. Hide the implementation of macros by disallowing access(undef or otherwise) to the macros inside the macro which we want to hide the implementation of.
1 Answers

When using GNU CPP you could use #pragma GCC poison, for example:

#include <stdio.h>

#define print(...) printf(__VA_ARGS__)
#pragma GCC poison printf

int
main ()
{
        print("hi, %s", "there!"); /* Ok */
        printf("oh %s", "no!"); /* ERROR! use of poisoned keyword */
}

Tested and it works!

Related