的覆盖弱功能的OS X和Android之间的共享库不同的行为不同、行为、功能、Android

2023-09-14 23:02:46 作者:忘不掉的回忆

我遇到了OS X和Android之间的不同的行为:

I am encountering a different behavior between OS X and Android:

有一个弱函数在我的共享库, 我想在我的可执行文件中定义功能强大覆盖它。 我希望被覆盖也影响到库里面的电话 There is a weak function foo in my shared library, I want to override it with strong function defined in my executable. I expect the the overridden also affect the calling inside the library

结果:我得到了预期的结果在OS X,但未能在Android

Result: I got expected result on OS X, but failed on Android.

下面是我的测试项目:

文件:shared.h

File: shared.h

void library_call_foo();
void __attribute__((weak)) foo();

文件:shared.c

File: shared.c

#include "shared.h"
#include <stdio.h>

void library_call_foo()
{
    printf("shared library call foo -> ");
    foo();
}

void foo()
{
    printf("weak foo in library\n");
}

文件:main.c中

File: main.c

#include <stdio.h>
#include <shared.h>

void foo()
{
    printf("strong foo in main\n");
}

int main()
{
    library_call_foo();
    printf("main call foo -> ");
    foo();
    return 0;
}

我编译和放大器;在OS X中使用命令运行它:

I compile & run it in OS X use commands:

clang -shared -fPIC -o libshared.so shared.c
clang -I. -L. -lshared -o test main.c
./test

而返回结果如我所料:

which return results as I expected:

shared library call foo -> strong foo in main
main call foo -> strong foo in main

但是,当我用NDK工具链编译为Android使用相同的命令:

But when I compile it for Android with NDK toolchains use same commands:

arm-linux-androideabi-clang -shared -fPIC -o libshared.so shared.c
arm-linux-androideabi-clang -I. -L. -lshared -o test main.c

和设备上运行它,我得到了不同的结果:

and run it on device, I got different results:

shared library call foo -> weak foo in library
main call foo -> strong foo in main

为什么行为是不同的,我怎么能解决这个问题?

Why is the behaviors are different, and how could I fix it?

推荐答案

Android的动态链接程序实际上是支持弱符号。问题是这种特殊的情况是,库编译-Bsymbolic(以检查此运行readelf -d libshared.so)。

Android dynamic linker does in fact support weak symbols. The problem is this particular case is that library is compiled with -Bsymbolic (to check this run "readelf -d libshared.so").

解决这个问题的工作是使用-Wl,-shared'而不是'-shared'链接库时。

The work around this is to use '-Wl,-shared' instead of '-shared' when linking the library.

请参阅 https://开头code。 google.com/p/android/issues/detail?id=68956 细节和解决办法。

Please see https://code.google.com/p/android/issues/detail?id=68956 for details and workaround.