![](/img/trans.png)
[英]Why does gcc -O3 handle avx256 compare intrinsic differently than gcc -O0 and 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.