c 函数别名

int test(int num) {

return num;

}

1.define

#define TEST test

TEST(33);


2.函数地址指针

int (*testv2)(int) = test;

testv2(33);


3.__attribute__ ((__weakref__(""))), 弱引用

static __typeof(test) testv3 __attribute__ ((_weakref_("test")))

if (testv3) {

testv3(33);

}

其中__typeof会返回变量或者函数的实际类型信息,如

int num;

__typeof(num) num1 = 1; // int

int test(int num) {

return 0;

}

__typeof(test) test1; // int (*test1)(int)


完整测试代码:

#include <stdio.h>

int test(int num) {
    return num;
}

#define TEST test

int (*testv2)(int) = test;

static __typeof(test) testv3 __attribute__((__weakref__("test")));

int main(int argc, char **argv) {
    // version 1
    printf("version 1 value %d\n", TEST(33));

    // version 2
    printf("version 2 value %d\n", testv2(33));

    // version 3
    if (testv3)
        printf("version 3 value %d\n", testv3(33));
    return 0;
}

注:

如果上诉测试代码version 3发现没有执行,那么请确认下自己是否是用g++进行编译的

如果是用g++进行编译,那么会出现test函数的名字是c++命名规范,而__weakref__("test")是以c命名规范,

因此要想在g++编译器下同样生效,可以在test函数外围包一层extern "C" {}即可



  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值