2012-12-24 78 views
5

我想允许在头文件中定义的.c文件中重新定义一个函数。根据GCC手册的weakref属性:这是weakref的正确用法吗?

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)

回答

1

就我所知,您需要将该函数定义为extern。 然后,它为我工作如下:

[email protected]:$ 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(); 
} 

[email protected]:$ gcc weakref.c 
[email protected]:$ ./a.out 
calling foo. 
default foo 
[email protected]:$ 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 
[email protected]:$ gcc -c weakrefUser.c 
[email protected]:$ gcc -c weakref.c 
[email protected]:$ gcc weakref.o weakrefUser.o 
[email protected]:$ ./a.out 
calling foo. 
user defined foo. 

注1:它不与静态函数工作,对弱者的属性,它必须是全球性的。注意2:ELF目标仅支持弱符号。

+0

'weak'和'weakref'是[两个不同的东西](https://gcc.gnu.org/onlinedocs/gcc-4.9.4/gcc/Function-Attributes.html#Function-Attributes)。问题是关于'weakref',你用'weak'回答。 – Nawaz