簡體   English   中英

為什么 gcc/clang 處理代碼略有不同? (給出的例子)

[英]Why does gcc/clang handle code slightly differently? (Example given)

所以我在搞亂 C 代碼,我注意到 gcc 和 clang 處理代碼的方式。

如果我使用可變大小在文件 scope 中聲明一個數組,則 clang 編譯沒有問題,但 gcc 會引發錯誤。 我的猜測是,它與 gcc/clang 中默認啟用/未啟用哪些編譯器標志有關,但如果有人能准確地告訴我為什么會發生這種情況並可能建議一些我可以學習的在線資源,我會很高興有關此功能的更多信息。

這是引發錯誤的代碼的任意示例 -

typedef struct node{
    int data;
    struct node *next;
    struct node *prev;
}node;

const int N = 1000;
node *table[N]; // This is where the error is

int main() {
    return 0;

running clang example.c with no other flags compiles fine running gcc example.c with no other flags throws an error -

example.c:9:7: error: variably modified 'table' at file scope
    9 | node *table[N];
      |       ^~~~

N看起來像一個常數,但實際上並非如此。 const的意思是“我發誓我不會改變這個變量的值”(否則編譯器會提醒我。); 但這並不意味着它不能以我在這個編譯單元中看不到的另一種方式改變。 因此這並不完全是一個常數。

gcc似乎對標准非常嚴格,但使用選項-pedantic會使clang發出警告。

$ clang -o prog_c prog_c.c -pedantic
prog_c.c:12:14: warning: variable length array folded to constant array as an extension [-Wgnu-folding-constant]
double table[N];
             ^
1 warning generated.

$ clang -o prog_c prog_c.c -pedantic -std=c90
prog_c.c:12:13: warning: variable length arrays are a C99 feature [-Wvla-extension]
double table[N];
            ^
prog_c.c:12:8: warning: size of static array must be an integer constant expression [-Wpedantic]
double table[N];
       ^
2 warnings generated.

$ clang -o prog_c prog_c.c -pedantic -std=c99
prog_c.c:12:8: warning: size of static array must be an integer constant expression [-Wpedantic]
double table[N];
       ^
1 warning generated.

根據您使用的gcc的版本,它默認為 C90(帶有一些擴展),並且可變長度 arrays 不是 C90 的一部分。

如果您指定-std=c99-std=c11 ,它應該支持 VLA。

但是,根據 C 語言定義,VLA 不能具有static存儲持續時間(就像在文件 scope 中聲明的數組一樣)。 所以clang必須將N視為常量表達式(很像 C++ 所做的),並且數組是固定長度的,而不是可變長度的。 到目前為止,我還沒有在clang文檔中找到任何可以表明這一點的內容。

使用選項-std=c11 -pedantic運行兩個編譯器,看看是否沒有得到相同的錯誤。

暫無
暫無

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

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