簡體   English   中英

強制編譯器符合C99標准

[英]Forcing compiler to C99 standard

當我發現我已經使用了一段時間的匿名結構實際上只能在C11中使用,而不是C99時,我正在對我的項目進行編碼,這是我想編寫的標准。

給出以下代碼:

struct data {
    int a;
    struct {
        int b;
        int c;
    };
};

int main()
{
    struct data d;

    d.a = 0;
    d.b = 1;
    d.c = 2;
    return 0;
}

此代碼應僅在C11中編譯(或者如果編譯器擴展提供此功能並且已啟用)。 那么讓我們看看不同編譯器的結果:

鏗鏘5

compiler:
    Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
    Target: x86_64-apple-darwin13.1.0
    Thread model: posix
command: 
    clang -std=c99 -Wall test.c -o test
result: 
    **OK**

gcc 4.1

compiler:
    gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-54)
command: 
    gcc -std=c99 -Wall test.c -o test
result: 
    **NOT OK**
    test.c:6: warning: declaration does not declare anything
    test.c: In function 'main':
    test.c:14: error: 'struct data' has no member named 'b'
    test.c:15: error: 'struct data' has no member named 'c'

gcc 4.7

compiler:
    gcc (GCC) 4.7.2 20121109 (Red Hat 4.7.2-8)
command: 
    gcc -std=c99 -Wall test.c -o test
result: 
    **OK**
    test.c: In function 'main':
    test.c:11:14: warning: variable 'd' set but not used [-Wunused-but-set-variable]

我總是試圖通過指定-std=c99強制編譯器進入C99模式,但顯然這不起作用(gcc 4.1除了沒有-std參數編譯好)。 所以現在我的問題是,如果我編寫的代碼不符合我使用-std指定的標准,我怎么能強制編譯器gcc和clang在任何版本中發出錯誤? 是否有一些我不知道的命令行參數?

-std=c99不會禁用語言擴展(GNU C在C99中有結構)。

-pedantic (或-pedantic-errors )標志使編譯器對語言擴展發出警告。

gccclang允許大量的擴展這里是clang clang一般試圖支持gcc所做的大多數擴展。 雙方甚至會允許你使用C僅在C ++例如功能VLAS這是C99的功能

在這種情況下,兩者都允許您在C99模式下的結構/聯合中使用未命名的struct / union字段,即使它是C11功能。

GCC支持語言標准很好地記錄了將這些變成警告和錯誤所需的標志,據我所知, clang遵循相同的約定:

[...]要獲得標准所需的所有診斷,您還應指定-pedantic(或-pedantic-errors,如果您希望它們是錯誤而不是警告)。 [...]

如果您使用擴展名,那么-pedantic會警告您, -pedantic-errors會將這些警告變成錯誤。 使用-pedantic標志你應該在gcc看到這樣的警告:

警告:ISO C99不支持未命名的結構/聯合[-Wpedantic]

這是在clang現場直播 ):

警告:匿名結構是C11擴展名[-Wc11-extensions]

它會變成帶有-pedantic-errors

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM