在 Linux 系统中如何查看和指定 C 语言标准

在Linux中,可以通过`gcc-E-dM/dev/null|grepSTDC_VERSION`命令查看GCC支持的C语言标准。C语言的标准包括C89、C99、C11和C17。默认情况下,GCC使用-std=gnu11。若要指定标准,如C89,需使用`gccmain.c-otest-std=c89`,不支持for循环内声明变量的C89标准会导致编译错误,需切换至C99或更高标准。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文主要介绍在 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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿基米东

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值