2012-12-24 24 views
5

Tôi muốn cho phép xác định lại chức năng trong tệp .c đã được xác định trong tệp tiêu đề. Theo hướng dẫn GCC về thuộc tính weakref:Đây có phải là cách sử dụng chính xác của weakref không?

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.

Âm thanh chính xác như những gì tôi muốn làm. Tuy nhiên, ví dụ sau đây không biên dịch với lỗi:

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(); 
} 

Tôi sử dụng này một cách chính xác? Tôi đang thiếu gì?

gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)

Trả lời

1

Theo tôi hiểu rằng bạn cần xác định hàm đó làm bên ngoài. Sau đó, nó làm việc cho tôi như sau:

[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. 

Note1: Nó không làm việc với chức năng tĩnh, cho thuộc tính yếu, nó cần phải được toàn cầu.

Lưu ý2: Các ký hiệu yếu chỉ được "hỗ trợ" cho các mục tiêu ELF.

+0

'yếu' và' weakref' là [hai thứ khác nhau] (https://gcc.gnu.org/onlinedocs/gcc-4.9.4/gcc/Function-Attributes.html#Function-Attributes). Câu hỏi là về 'weakref' và bạn trả lời bằng cách sử dụng' weak'. – Nawaz

Các vấn đề liên quan