1

I want to backup macro value like below.

g++ ... -D_XOPEN_SOURCE=600 current _XOPEN_SOURCE value is 600

// xxx.h
#define _XOPEN_SOURCE 700 // redefine
#ifdef _XOPEN_SOURCE // 600
#define _XOPEN_SOURCE_BACK _XOPEN_SOURCE 
#undef _XOPEN_SOURCE // removed
#endif

#include "xxx.h" // changed to 700
// _XOPEN_SOURCE_BAKC will be changed to 700
#ifdef _XOPEN_SOURCE_BACK
#undef _XOPEN_SOURCE // removed
#define _XOPEN_SOURCE _XOPEN_SOURCE_BACK 
#endif

But as you know the _XOPEN_SOURCE_BACK value will be removed when #undef _XOPEN_SOURCE Is there any solution to store _XOPEN_SOURCE value using macro?

How to backup #define macro value in C?

킵고잉
  • 11
  • 2

2 Answers2

2

There is no way to do so in standard C, but gcc has an extension:

 #pragma push_macro("_XOPEN_SOURCE")
 #undef _XOPEN_SOURCE

 ...

 #pragma pop_macro("_XOPEN_SOURCE")
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
1

Maybe you can use an enum (a real constant known at compile time):

#include <stdio.h>

#define _XOPEN_SOURCE 600

enum { _XOPEN_SOURCE_BACK =
#ifdef _XOPEN_SOURCE // 600
    _XOPEN_SOURCE
#undef _XOPEN_SOURCE // removed
#else
    0
#endif
};

#define _XOPEN_SOURCE _XOPEN_SOURCE_BACK // redefine

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

Output:

600
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • 1
    `_XOPEN_SOURCE` is a feature test macro, only to be used in the preprocessor `#if` or `#ifdef` directives. – n. m. could be an AI Jul 30 '23 at 08:55
  • Thank you for your effort. I have a question about your solution. Can I remove the enum value from memory after setting up the _XOPEN_SOURCE? Actually, I don't want to waste memory. – 킵고잉 Jul 31 '23 at 09:39
  • @킵고잉 Hi, you are welcome, and no, you can not remove the enum value from memory, are you aware that the size of an `enum` with a single element is 4 bytes? (same than if you declare `int OPEN_SOURCE_BACK = 600;` in size). – David Ranieri Jul 31 '23 at 16:13