开始学习
GCC 查看及指定 C 语言标准
本文主要介绍在 Linux 系统中如何查看当前支持的 C 语言版本,以及在编译时如何指定 C 语言标准。
目前常见的 C 语言标准有 C89、C99、C11 和 C17,详情可参考《C语言标准》。
查看 C 语言标准
我们可以通过 gcc 命令查看当前支持的 C 语言标准,具体命令如下:
gcc -E -dM - </dev/null | grep "STDC_VERSION"
输出结果和 C 标准的对应关系如下:
如果是 #define __STDC_VERSION__ 199901L
,则默认支持的是 C99 标准;
如果是 #define __STDC_VERSION__ 201112L
,则默认支持的是 C11 标准;
如果是 #define __STDC_VERSION__ 201710L
,则默认支持的是 C17 标准;
如果没查到,则默认支持的是 C89 标准。
指定 C 语言标准编译
当我们查询到当前 GCC 编译器支持的 C 语言标准后,如果想在编译时指定 C 语言标准,可以使用 -std
选项参数进行指定,常用的(非全部)选项如下:
-std=c17 # Conform to the ISO 2017 C standard
-std=c11 # Conform to the ISO 2011 C standard
-std=c99 # Conform to the ISO 1999 C standard
-std=c90 # Conform to the ISO 1990 C standard
-std=c89 # Conform to the ISO 1990 C standard
-std=gnu17 # Conform to the ISO 2017 C standard with GNU extensions
-std=gnu11 # Conform to the ISO 2011 C standard with GNU extensions
-std=gnu99 # Conform to the ISO 1999 C standard with GNU extensions
-std=gnu90 # Conform to the ISO 1990 C standard with GNU extensions
-std=gnu89 # Conform to the ISO 1990 C standard with GNU extensions
在 Linux 系统中,默认情况下如果不指明 -std
选项,GCC 会使用 -std=gnu11
作为默认支持的 C 语言版本,也就是 C11 标准加上 GCC extension 的组合。
例如,程序 main.c 如下:
#include <stdio.h>
int main()
{
for(int i=0; i<10; i++)
{
printf("%d\n", i);
}
return 0;
}
指定 C89 标准编译
gcc main.c -o test -std=c89
会出现如下错误
main.c: In function ‘main’:
main.c:5:5: error: ‘for’ loop initial declarations are only allowed in C99 or C11 mode
5 | for(int i=0; i<10; i++)
| ^~~
main.c:5:5: note: use option ‘-std=c99’, ‘-std=gnu99’, ‘-std=c11’ or ‘-std=gnu11’ to compile your code
这是因为 C89 标准不支持在 for
循环中声明变量 i
,指定 C99 标准再次编译则不会有问题。
gcc main.c -o test -std=c99