我是 Linux gcc 的新手。我正在编写一个简单的代码来学习 Linux gcc 中的弱属性。
查看我的示例代码:
weakref.c,主文件。我希望文件可以在定义或不定义 foo 方法的情况下工作。
#include <stdio.h>
extern void foo(void) __attribute__((weak));
int main() {
if (foo){
foo();
printf ("foo is defined\n");
} else {
printf("foo is not defined\n");
}
}
所以,我运行以下命令来编译它并运行它:
gcc weakref.c -o main_static
./main_static
并且输出是“foo is not defined”,这是我所期望的。
然后我创建了一个新文件 libfoo.c,见下图:
#include <stdio.h>
void foo() {
printf("Print in foo.\n");
}
我尝试了 3 种方法来尝试使主文件与 libfoo.c 一起使用:
- 编译 libfoo.c 和 weakref.c 并链接目标文件。
- 将libfoo.c编译为静态库,并与weakref.c的目标文件链接
- 将libfoo.c编译为共享库,并与weakref.c的目标文件链接
只有第三种方式有效并获得以下输出:
Print in foo.
foo is defined
您能否让我知道弱引用是否仅适用于共享库,为什么?非常感谢!