__attribute__((deprecated)) 函数属性

本文介绍C语言中使用__attribute__((deprecated))函数属性标记废弃函数的方法,包括其语法、示例代码及编译警告信息。适用于代码版本升级后的API重命名,帮助开发者及时更新代码。

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

1、此函数属性指示存在某个函数,

    如果使用了 deprecated 属性修饰的函数,则编译器必须生成警告。

    如果未使用该属性修饰的函数则不会产生任何警告

2、在GNU模式下,这个属性接受一个可选的字符串参数来显示在消息中,即:

__attribute__((deprecated("message")))

3、例程

#include <stdio.h>

 __attribute__((deprecated("Function_Attributes_deprecated_0 is renamed to func_dec()"))) int Function_Attributes_deprecated_0(int b)
{
    return b++;
}

int main(int argc, char *argv[])
{
    Function_Attributes_deprecated_0(2);

    int choice = 2;
    switch (choice)
    {
    case 1:
        printf("This is case 1.\n");
        break;
    case 2:
        printf("This is case 2.\n");
        __attribute__((fallthrough));
    case 3:
        printf("This is case 3.\n");
        break;
    default:
        printf("Invalid choice.\n");
        break;
    }

    return 0;
}

4、编译结果

test.c: In function ‘main’:
test.c:10:5: warning: ‘Function_Attributes_deprecated_0’ is deprecated: Function_Attributes_deprecated_0 is renamed to func_dec() [-Wdeprecated-declarations]
   10 |     Function_Attributes_deprecated_0(2);
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test.c:3:95: note: declared here
    3 |  __attribute__((deprecated("Function_Attributes_deprecated_0 is renamed to func_dec()"))) int Function_Attributes_deprecated_0(int b)

产生了警告,提示该函数已经废弃

5、使用场景

代码版本升级时,将 API 重命名了,那么当程序中还在使用旧的 API 名称时就会产生警告,提示用户使用新的 API

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

tyustli

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

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

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

打赏作者

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

抵扣说明:

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

余额充值