把#warning放在#define的体内

时间:2011-01-21 03:13:21

标签: c++ c visual-studio-2010 mingw

在一个应该能够在C和C ++文件中编译的头文件中,在Visual Studio(2010)和MinGW(32位 - v3.4.5,64位 - v4.5.0)中我试图最小化大小通过改变这一行中的每一行(其中有很多):

// for symbol A
#ifdef __GNUC__
# warning Symbol A is deprecated. Use predefined const cnA instead.
#else
# pragma message("Symbol A is deprecated. Use predefined const cnA instead.")
#endif

// Same for B
// Same for C
// . . . 

// define this once:
#ifdef __GNUC__
# define X_Warning(x) #warning "Symbol " x " is deprecated. Use cn" x  // (1)
#else
# define X_Warning(x) __pragma(message("Symbol " x " is deprecated. Use cn" x "))
#endif

// and use like this:
X_Warning("A")
X_Warning("B")
X_Warning("C")

或者,至少对此:

// define this once:
#ifdef __GNUC__
# define Y_Warning(x) #warning x   // (2)
#else
# define Y_Warning(x) __pragma(message(x))
#endif

// and use like this:
Y_Warning("Symbol A is deprecated. Use predefined const cnA instead.")
Y_Warning("Symbol B is deprecated. Use predefined const cnB instead.")
Y_Warning("Symbol C is deprecated. Use predefined const cnC instead.")
. . .

但标有(1)的行不起作用。

__pragma是微软相当于#pragma在这种情况下使用的。

  1. 这样做的正确方法是什么?
  2. MinGW / gcc甚至可能吗?
  3. __GNU__用于此类事情的正确符号吗?
  4. P.S。我忘了提到A,B,C ..是#defined-ed符号。在这种情况下,不可能使用我的旧MinGW v3.4.5(至少在我的情况下使用此特定配置)。而@ Edwin的回答是正确的。

    但_Pragma受到更新版MingW的支持,感谢@Christoph的回答,可以这样做:

    // define this once:
    #ifdef __GNUC__
    # define DO_PRAGMA(x) _Pragma (#x)
    # define X_Warning(x) DO_PRAGMA( message "Symbol " #x " is deprecated. Use cn" x )
    #else
    # define X_Warning(x) __pragma(message("Symbol " x " is depricated. Use cn" x ))
    #endif
    
    // and use like this:
    #ifdef A
      X_Warning("A")
    #endif
    #ifdef C
      X_Warning("B")
    #endif
    #ifdef B
      X_Warning("C")
    #endif
    

    在某些情况下,标记为已弃用似乎有效,但对我而言则不然。它要求您在使用之前定义已弃用的符号,这不是我的情况,而是我无法控制的。

3 个答案:

答案 0 :(得分:4)

在msvs 2010中有这样的:

 #pragma deprecated( identifier1 [,identifier2, ...] )

不了解其他编译器

和microsoft特定:

__declspec(deprecated) void func1(int) {}
__declspec(deprecated("** this is a deprecated function **")) void func2(int) {}
__declspec(deprecated(MY_TEXT)) void func3(int) {}

答案 1 :(得分:4)

GCC支持C99 _Pragma运算符,甚至还附带example code for your use case

答案 2 :(得分:3)

您无法使用宏构建#pragma或#warning,但我认为您可以执行以下操作:

#ifdef __GNUC__
# define Y_Warning(x) message x
#else
# define Y_Warning(x) message(x)
#endif

#pragma Y_Warning("Symbol A is depreboned. Use predefined const cnA instead.")
#pragma Y_Warning("Symbol B is depronated. Use predefined const cnB instead.")
#pragma Y_Warning("Symbol C is deprecuted. Use predefined const cnC instead.")