2013-01-17 51 views
1

我不明白爲什麼這個工程:GCC的typeof擴展

/* gcc range extension */ 
__extension__ static int fn(int n) 
{ 
    switch (n) { 
     case 0: return 0; 
     case 1 ... 1000: return 1; 
     default: return -1; 
    } 
} 

但這並不:

/* gcc typeof extension */ 
__extension__ static void fn(int n) 
{ 
    typeof(n) a = n; 

    printf("%d\n", a); 
} 

GCC回報:

demo.c:14: warning: implicit declaration of function ‘typeof’ 
demo.c:14: warning: nested extern declaration of ‘typeof’ 
demo.c:14: error: expected ‘;’ before ‘a’ 
demo.c:16: error: ‘a’ undeclared (first use in this function) 
demo.c:16: error: (Each undeclared identifier is reported only once 
demo.c:16: error: for each function it appears in.) 

我知道我可以編譯-std=gnu99以避免錯誤,但第一個與-std=c99一起使用,並使用擴展

回答

8

通過__extension__不能重新使用非ANSI兼容關鍵字(__extension__的唯一影響是-pedantic的警告抑制)。如果要在ANSI模式下編譯,請使用__typeof__

+1

哇!!!!那麼'#define typeof __typeof__'避免了這個問題? –

+1

@大衛:是的,它應該。 :) – askmish

+0

謝謝安東和askmish;) –

2

如果您正在編寫包含在ISO C程序中的必須工作的頭文件,請寫__typeof__而不是typeof

請參閱此link瞭解更詳細的說明和可能的修復。

注意:使用ANSI C -pedantic模式時,除了禁止警告之外,__extension__不起作用。

因此,像這樣:

/* gcc typeof extension */ 
__extension__ static void fn(int n) 
{ 
    __typeof__(n) a = n; 

    printf("%d\n", a); 
} 
+0

感謝您的回答和鏈接 –