为什么 gcc/clang 处理代码的方式略有不同? (给出的例子)

2023-12-07

所以我在摆弄 C 代码时,我注意到 gcc 和 clang 处理代码的方式。

如果我使用可变大小在文件范围中声明一个数组,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没有其他标志编译运行良好gcc example.c没有其他标志会引发错误 -

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

N看起来像是一个常数,但事实并非如此。 这const意思是“我发誓我不会改变这个变量的值”(否则编译器会提醒我!)。 但这并不意味着它不能通过我在这个编译单元中没有看到的另一种方式来改变;因此这并不完全是一个常数。

gcc似乎对标准非常严格,但使用选项-pedantic makes 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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 gcc/clang 处理代码的方式略有不同? (给出的例子) 的相关文章

随机推荐