OS X 和 Android 共享库中覆盖弱函数的不同行为 [英] Different behavior of override weak function in shared library between OS X and Android

查看:15
本文介绍了OS X 和 Android 共享库中覆盖弱函数的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  • 我的共享库中有一个弱函数foo
  • 我想用我的可执行文件中定义的强函数覆盖它.
  • 我希望被覆盖的也会影响库内的调用

结果:我在 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
");
}

文件:main.c

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

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

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

按预期返回结果:

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.

这篇关于OS X 和 Android 共享库中覆盖弱函数的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆