gpt4 book ai didi

c - 这是 weakref 的正确用法吗?

转载 作者:太空狗 更新时间:2023-10-29 15:08:18 24 4
gpt4 key购买 nike

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

The effect is equivalent to moving all references to the alias to a separate translation unit, renaming the alias to the aliased symbol, declaring it as weak, compiling the two separate translation units and performing a reloadable link on them.

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

tpp.c:18:13: error: redefinition of ‘foo’ tpp.c:6:13: note: previous definition of ‘foo’ was here

#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 version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)

最佳答案

据我了解,您需要将该函数定义为 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 目标“仅”支持弱符号。

关于c - 这是 weakref 的正确用法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14024593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com