【问题标题】:Is this correct usage of weakref?这是弱引用的正确用法吗?
【发布时间】:2012-12-24 18:27:38
【问题描述】:

我想允许重新定义已在头文件中定义的 .c 文件中的函数。根据 GCC 手册上的 weakref 属性:

效果相当于将所有对别名的引用移动到单独的翻译单元,将别名重命名为别名符号,将其声明为弱,编译两个单独的翻译单元并对其执行可重新加载的链接。

这听起来正是我想要做的。 但是,以下示例编译时不会出错:

tpp.c:18:13: 错误:“foo”的重新定义 tpp.c:6:13: 注意:之前对‘foo’的定义在这里

#include <sys/types.h>
#include <stdio.h>

/* this will be in a header file */
static void foo(void) __attribute__ ((weakref ("_foo")));

static void _foo(void)
{
    printf("default foo\n");
}

/* in a .c file #including the header mentioned above */
#define CUSTOM_FOO

#ifdef CUSTOM_FOO
static void foo(void)
{ 
    printf("user defined foo.\n");
}
#endif

int main(int argc, char **argv)
{
    printf("calling foo.\n");
    foo();
}

我使用正确吗?我错过了什么?

gcc 版本 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)

【问题讨论】:

    标签: c gcc


    【解决方案1】:

    据我了解,您需要将该函数定义为 extern。 然后它对我的工作如下:

    user@horst:$ cat weakref.c
    
    #include <sys/types.h>
    #include <stdio.h>
    
    /* this will be in a header file */
    extern void foo(void) __attribute__ ((weak, alias ("_foo")));
    
    void _foo(void)
    {
        printf("default foo\n");
    }
    
    int main(int argc, char **argv)
    {
        printf("calling foo.\n");
        foo();
    }
    
    user@horst:$ gcc weakref.c 
    user@horst:$ ./a.out 
    calling foo.
    default foo
    user@horst:$ cat weakrefUser.c
    #include <stdio.h>
    /* in a .c file #including the header mentioned above */
    #define CUSTOM_FOO
    
    #ifdef CUSTOM_FOO
    void foo(void)
    { 
        printf("user defined foo.\n");
    }
    #endif
    user@horst:$ gcc -c weakrefUser.c 
    user@horst:$ gcc -c weakref.c 
    user@horst:$ gcc weakref.o weakrefUser.o 
    user@horst:$ ./a.out 
    calling foo.
    user defined foo.
    

    注意1:它不适用于静态函数,对于弱属性,它需要是全局的。

    注意 2:ELF 目标“仅”支持弱符号。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 2014-02-16
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多