由于 -allow-shlib-undefined 链接器开关而产生的符号查找错误是否有任何解决方案?

Is there any solution of symbol lookup error that is produced because of -allow-shlib-undefined linker switch?

我想了解 gnu linker 的“-allow-shlib-undefined”开关的用法。 为此,我写了libfoo.so和libfunc.so。

//libfoo.h
void say_hello(void);
//libfoo.c
#include <stdio.h>
#include "libfoo.h"
#include "libfunc.h"

void say_hello(void)
{
   printf("Hello\n");
   say_goodbye();
}
//libfunc.h
void say_goodbye(void);
//libfunc.c
#include <stdio.h>
#include "libfunc.h"

void say_goodbye(void)
{
    printf("Goodbye!\n");
}

然后我使用以下 gcc 命令编译 libfoo 和 libfunc:

gcc -c libfoo.c -o libfoo.o
gcc -shared -o libfoo.so libfoo.o

gcc -c libfunc.c -o libfunc.o
gcc -shared -o libfunc.so libfunc.o 

然后我写了以下“主要”代码:

#include "libfoo.h"
int main(void) {
    say_hello();
}

然后我尝试使用以下 gcc 命令编译此代码:

gcc -L<path-to-libs> main.c -o main -lfoo

如我所料,此命令发生错误。(因为我没有link libfunc.so) 然后我用下面的 gcc 命令编译 main.c:

gcc -L<path-to-libs> -Wl,-allow-shlib-undefined main.c -o main -lfoo

使用此命令编译成功。但是当我 运行 main 我得到以下错误:

Hello
./main: symbol lookup error: /home/sarslan/shlib-undefined/libfoo.so: undefined symbol: say_goodbye

有什么办法可以解决这个错误吗?

Is there any way to solve this error ?

是:该标志是打算用于您知道缺少的功能将在提供的情况runtime,但是(无论出于何种原因)您无法在 link time.

提供其定义

要使您的程序运行,您必须在运行时提供不同的 libfoo.so或者

  1. 不调用 say_goodby(),或
  2. 提供了自己对 say_goodby() 的定义。

或者,您可以使用 LD_PRELOAD=./libfunc.so.

修复运行时错误

注意:使用 LD_PRELOAD 有很多潜在的并发症,而且几乎不是正确的解决方案。

P.S。您正在构建没有 -fPIC 的共享库。这在许多体系结构上都不起作用,并且在它确实起作用的系统上不是最优的。