当我在编写我的项目时,我发现我已经使用了一段时间的匿名结构体实际上只有在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]
我一直尝试通过指定-std=c99
来强制编译器进入C99模式,但很明显这并不起作用(除了gcc 4.1可以在没有-std参数的情况下编译)。
所以我的问题是,如何强制编译器gcc和clang,在任何版本中,如果我编写的代码不符合使用-std
指定的标准,则发出错误信息?是否有一些我不知道的命令行参数?
c99
代替gcc
仍然可以编译通过,而它本应该失败... - grasbueschel-pedantic
标志来警告语言扩展(GNU C在C99中有匿名结构体)。也许这个关于/usr/bin/c99
的答案对你有用。 - MBlanc-pedantic
,我得到了一个警告,说我使用了非 C99 特性。由于这只是一个警告,它仍然可以编译,但这比没有好(希望它是一个错误)。请将此评论再次发布为答案,我很乐意接受!谢谢! - grasbueschel-Werror
标志将(所有)警告变成错误。 - Kninnug