当我在我的项目上编码时,我发现我已经使用了一段时间的匿名结构实际上只在 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 中编译(或者编译器扩展提供此功能并启用)。那么让我们看看不同编译器上的结果:
clang 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]
我一直尝试通过指定强制编译器进入 C99 模式-std=c99
,但显然这不起作用(除了 gcc 4.1,它在没有 -std 参数的情况下编译良好)。
所以我现在的问题是,如果我编写的代码不符合我指定的标准,如何强制编译器 gcc 和 clang 在任何版本中发出错误-std
?是否有一些我不知道的命令行参数?
-std=c99
不会禁用语言扩展(GNU C 在 C99 中有匿名结构)。
The -pedantic http://clang.llvm.org/docs/UsersManual.html#cmdoption-pedantic (or -pedantic-errors http://clang.llvm.org/docs/UsersManual.html#cmdoption-pedantic-errors) 标志使编译器对语言扩展发出警告。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)