C Macro to protect definitions

笑着哭i 提交于 2019-12-11 09:09:24

问题


Is there a way to protect a macro definition? To be more specific consider the following:

#define macro1 x

// code segment 1 involving macro1 goes here 

// code segment 2 involving macro1 goes here

// code segment 3 involving macro1 goes here

In the example I have placed 3 comments denoting code segments involving the macro. What I would like to do now is to be able to avoid having the macro affect code segment 2. Is there a way to tell the compiler to replace all instances of macro1 in segment 1 and segment 3 but not in segment 2? Here is a possible way:

#define macro1 x

// code segment 1 involving macro1 goes here 

#undef macro1

// code segment 2 involving macro1 goes here

#define macro1 x

// code segment 3 involving macro1 goes here

The drawback is that I have to define the macro again. Say I wanted to use the word NULL in my program (don't ask me why just go with it). I want this to be a variable but the C preprocessor will change it to 0 in most cases. So what I want to do, is to be able to block it for just a short time period and then let it be what it was before.

Failed Attempt:

Let us suppose that macro1 has been defined somewhere externally and we do not even know what the value of such macro is. All we want is to avoid having it replace things in the second segment.

// code segment 1 involving macro1 goes here 

#ifdef macro1
#define TEMP macro1
#undef macro1
#endif

// code segment 2 involving macro1 goes here

#ifdef TEMP
#define macro1 TEMP
#undef TEMP
#endif

// code segment 3 involving macro1 goes here

The idea is to check if the macro exists, if it does, then we want to store the value into another variable, undefine the macro and finally define the macro again when we need it. Unfortunately, this code doesn't work because before we execute code segment 3 macro1 will be replaced by TEMP, not the value that TEMP was supposed to have.


回答1:


The easiest way to have a chunk of code not be impacted by a macro is to put the macro in a header .h file and NOT include the header file in the source file that is getting compiled.

This means you might have to "chop up" a bigger file to get your section of code that shouldn't be impacted by the macro out. Yes, it is a pain, but it sounds like it shouldn't be with the rest of the code anyway (or it wouldn't be an issue).




回答2:


GCC and MSVC allow you to use a pragma to push and pop macro definitions:

 #define X  1
 #pragma push_macro("X")
 #undef X
 #define X -1
 #pragma pop_macro("X")
 int x [X];
  • http://msdn.microsoft.com/en-us/library/hsttss76.aspx
  • http://gcc.gnu.org/onlinedocs/gcc/Push_002fPop-Macro-Pragmas.html


来源:https://stackoverflow.com/questions/9402174/c-macro-to-protect-definitions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!