2012-12-24 6 views
5

すでにヘッダーファイルで定義されている.cファイルの関数の再定義を許可します。 GCCのweakref属性に関するマニュアルによると、これは私がしたいこととまったく同じように思えますが、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」は「2つの異なるもの」です(https://gcc.gnu.org/onlinedocs/gcc-4.9.4/gcc/Function-Attributes.html#Function-Attributes)。質問は 'weakref'に関するもので、あなたは' weak'を使って答えました。 – Nawaz

関連する問題