2011-11-16 48 views
19

我試圖在不向我咆哮的情況下完成此工作(在GCC 4.6中)。在重新定義時暫時禁用gcc警告

#define FOO "" 
#define BAR "" 

#if .... 
    #define FOO "Foo, good sir" 
#endif 

#if ... 
    #define BAR "Bar, my lady" 
#endif 
.... 

#define EVERYTHING  FOO BAR ... 

我將不得不這些很多。這樣做,而不是:

#if ... 
    #define FOO "Foo" 
#else 
    #define FOO "" 
#endif 

保存了很多代碼,並使其更具可讀性。我得到的警告是:警告

「FOO」重新定義

[默認啓用]有沒有一種方法來禁用代碼此警告這個特定部分?我發現Diagnostic Pragmas禁用了某些警告,但我無法找到需要在此禁用的警告(在此列表中的Options to Request or Suppress Warnings)。

任何人都知道如何做到這一點?或者以不同的方式來避免必須將所有的#else #define都添加到空字符串中?

+8

你可以用'-Wp,-w'禁用[預處理警告(http://gcc.gnu.org/onlinedocs/cpp/Invocation.html#Invocation) – osgx

+1

這一警告來自蘇俄文件在gcc(2.95版本)中名爲「cccp.c」,並且不能關閉。仍然沒有選擇單獨禁用此警告[即使在git head,gcc/libcpp/macro.c]中(http://gcc.gnu.org/git/?p=gcc.git;a=blob;f= libcpp/macro.c; h = f3139590d5045b128709296d1abbb81753284f10; hb = HEAD#l2527)(和同一個文件的第2994行) – osgx

+0

@osgx如果您使該評論成爲答案,我想接受它。 –

回答

6

這一警告來自於海灣合作委員會評爲「cccp.c」文件(的2.95版本,是「蘇聯」這個文件?),並且它不能被關閉。即使在git頭文件gcc/libcpp/macro.c file(同一個文件的2527和line 2994)中,仍然沒有單獨禁用這個警告的選項。

我會引用一些資源。

2525 /* Returns nonzero if a macro redefinition warning is required. */ 
2526 static bool 
2527 warn_of_redefinition (cpp_reader *pfile, cpp_hashnode *node, 
2528      const cpp_macro *macro2) 
2529 { 
... 
2537 /* Suppress warnings for builtins that lack the NODE_WARN flag. */ 
.. 
2545 /* Redefinitions of conditional (context-sensitive) macros, on 
2546  the other hand, must be allowed silently. */ 
... 
2550 /* Redefinition of a macro is allowed if and only if the old and new 
2551  definitions are the same. (6.10.3 paragraph 2). */ 
... 
2561 /* Check parameter spellings. */ 
... 
2566 /* Check the replacement text or tokens. */ 
... 
2573 for (i = 0; i < macro1->count; i++) 
2574  if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i])) 
2575  return true; 

所以在你的情況下warn_of_redefinition函數將返回true。這裏是實際用法:

2989 if (node->type == NT_MACRO) 
2990  { 
2991  if (CPP_OPTION (pfile, warn_unused_macros)) 
2992   _cpp_warn_if_unused_macro (pfile, node, NULL); 
2993 
2994  if (warn_of_redefinition (pfile, node, macro)) 
2995   { 
2996   const int reason = (node->flags & NODE_BUILTIN) 
2997        ? CPP_W_BUILTIN_MACRO_REDEFINED : CPP_W_NONE; 
2998   bool warned; 
2999 
3000   warned = cpp_pedwarning_with_line (pfile, reason, 
3001            pfile->directive_line, 0, 
3002            "\"%s\" redefined", 
3003            NODE_NAME (node)); 
3004 
3005   if (warned && node->type == NT_MACRO && !(node->flags & NODE_BUILTIN)) 
3006    cpp_error_with_line (pfile, CPP_DL_NOTE, 
3007         node->value.macro->line, 0, 
3008       "this is the location of the previous definition"); 
3009   } 
3010  } 

所以,沒有任何具體的選項。 Greg的回答對於這種情況非常有用,只是在重新定義之前取消定義空字符串。

+9

在蘇聯俄羅斯,宏重新定義你! – einpoklum

31

嘗試使用#undef

#define FOO "" 

#if .... 
    #undef FOO 
    #define FOO "Foo, good sir" 
#endif 
0

或嘗試使用if else。

#if ... 
# define FOO "Foo, doof sir" 
#else 
# define FOO "" 
#endif