您的位置:首页 > 编程语言 > C语言/C++

c语言之函数或者变量的weak属性

2015-08-28 09:57 309 查看
转自:http://blog.chinaunix.net/uid-20593827-id-1918496.html

c语言之函数或者变量的weak属性

gcc reference里提到:

A function with this attribute has its name emitted as a weak

symbol instead of a global name. This is primarily for the naming

of library routines that can be overridden by user code.

weak symbol

Having two or more global symbols of the same name will not cause a conflict as long as all but one of them are declared as being weak symbols. The linker ignores the definitions of the weak symbols and uses the normal global symbol definition to resolve all
references, but the weak symbols will be used if the normal global symbol is not available. A weak symbol can be used to name functions and data that can be overridden by user code. A weak symbol is also referred to as a weak alias, or simply weak.

通过简单的例子可以看出,weak属性可以让编译器在编译的时候忽略函数未定义的错误。

$cat weak.c

extern void foo() __attribute__((weak));

int main() {

if (foo) foo();

}

$ gcc weak.c-o weak

$ ./weak

$


weak alias 具有和weak symbol类似的作用。

int __centon() { return(100); }

void centon() __attribute__((weak,alias(“__centon”)));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: