c 函数别名

来源:互联网 发布:网络诗歌在哪里发布 编辑:程序博客网 时间:2024/05/21 19:48

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 testint (*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 0
原创粉丝点击