存储预处理器常量值然后通过undef / define'覆盖'

时间:2012-11-20 05:03:16

标签: c c-preprocessor

我试图存储预处理器常量的值,然后'覆盖'它。

我的问题:下面的代码尝试在变量“A”中存储预处理程序常量的值,然后代码取消定义该变量,然后重新定义它,使其具有新值。问题是变量'A'具有新定义的值而不是旧定义的值,如果这是有意义的。我可以存储预处理器常量值而不是它的引用(似乎正在发生这种情况)?

#ifdef CUSTOM_EVENT_CALLBACK_DEFINED
  #define SUB_CUSTOM_EVENT_CALLBACK_DEFINED CUSTOM_EVENT_CALLBACK_DEFINED
  #undef CUSTOM_EVENT_CALLBACK_DEFINED
#endif
#define CUSTOM_EVENT_CALLBACK_DEFINED "def"

int main()
{
    printf(CUSTOM_EVENT_CALLBACK_DEFINED);     // prints out "def". 
    printf("\n");
    printf(SUB_CUSTOM_EVENT_CALLBACK_DEFINED); // prints out "def". I was hoping this would be "abc"
    printf("\n");

    system("PAUSE");
    return 0;
}

// Usage: where the function def is a callback function for a window in a civil engineering program that runs ontop of windows
int def(int id, int cmd, int type)
{
    #ifdef SUB_CUSTOM_EVENT_CALLBACK_DEFINED
      SUB_CUSTOM_EVENT_CALLBACK_DEFINED(id, cmd, type);
    #endif

    // perform my custom code here
}

1 个答案:

答案 0 :(得分:2)

简短回答 - 不,这是不可能的。宏不是这样的。

但我怀疑你真的需要这样做。例如,解决方法是在覆盖变量之前将值存储在变量中:

#ifdef CUSTOM_EVENT_CALLBACK_DEFINED
  std::string SUB_CUSTOM_EVENT_CALLBACK_DEFINED = CUSTOM_EVENT_CALLBACK_DEFINED;
  #undef CUSTOM_EVENT_CALLBACK_DEFINED
#else
  std::string SUB_CUSTOM_EVENT_CALLBACK_DEFINED = "";
#endif

#define CUSTOM_EVENT_CALLBACK_DEFINED "def"

int main()
{
    printf(CUSTOM_EVENT_CALLBACK_DEFINED);     // prints out "def". 
    printf("\n");
    printf(SUB_CUSTOM_EVENT_CALLBACK_DEFINED); // prints out "def". I was hoping this would be "abc"
    printf("\n");

    system("PAUSE");
    return 0;
}

或者根本不使用宏。