[development] __attribute__((weak))是干嘛的

简单的说,就是当发生 “重复定义的时候”。被声明者会被冲突者覆盖掉。

这里还涉及了weak与alias连用的情况。

参见,里边有两个例子,很浅显易懂。

https://my.oschina.net/senmole/blog/50887

还有一个用法是,让未定义的函数在没实现的情况下,不影响程序的编译。

我自己写了个例子,如下:

[root@D128 examples]# cat test.c 
#include <stdio.h>
#include <stdint.h>

#ifdef _WEAK
extern void test_func2() __attribute__((weak));
#else
extern void test_func2();
#endif



void test_func()
{
    test_func2();
}


int main()
{
    return 0;
}
[root@D128 examples]# gcc test.c 
/tmp/ccm6AoTE.o: In function `test_func':
test.c:(.text+0xa): undefined reference to `test_func2'
collect2: error: ld returned 1 exit status
[root@D128 examples]# gcc -D_WEAK test.c 
[root@D128 examples]# 

但是,后一种的这个用法是一个很不推荐的用法,因为隐藏了不应该出现的错误。

在这种使用情况下,应该一定同时实现一个默认的函数。

[root@D128 examples]# cat test.c 
#include <stdio.h>
#include <stdint.h>

#ifdef _WEAK
extern void test_func2() __attribute__((weak));
#else
extern void test_func2();
#endif

void test_func()
{
    test_func2();
}


int main()
{
    test_func();
    return 0;
}

错误如下:

[root@D128 examples]# ./a.out 
Segmentation fault (core dumped)
原文地址:https://www.cnblogs.com/hugetong/p/8875486.html