Android NDK: how to link multiple 3rd party libraries

后端 未结 1 1244
星月不相逢
星月不相逢 2021-01-01 04:43

Let\'s say we\'re building a shared library A that needs to link to 2 external static libs B and C. All you\'ve got are libB.a and libC.a, along with their header files.

相关标签:
1条回答
  • 2021-01-01 05:28

    The answer can be found in How to deal with recursive dependencies between static libraries using the binutils linker?.

    LOCAL_LDLIBS := -L ../external/ -lB -lC -lB
    

    I took the two-libs NDK sample, and made minimal change to demonstrate the technique on GitHub.

    Update (2017): since 2012, the rules of NDK became more strict, and now it will complain that LOCAL_LDLIBS contains non-system libraries:

    Android NDK: WARNING:Android.module: non-system libraries in linker flags: -la -lb
    Android NDK: This is likely to result in incorrect builds. Try using LOCAL_STATIC_LIBRARIES
    Android NDK: or LOCAL_SHARED_LIBRARIES instead to list the library dependencies of the
    Android NDK: current module

    This is just a warning, so you can ignore it.

    Or add space after -l to outsmart the NDK protection:

    LOCAL_LDLIBS := -L ../external/ -l B -l C -l B
    

    Alternatively, you can use

    LOCAL_LDLIBS += -L ../external -Wl,--start-group -l B -l C -Wl,--end-group
    

    If the libraries that are involved are not prebuilt, you don't need to guess their location (which may be especially tricky when using Android Studio NDK integration). Use

    LOCAL_LDLIBS := -L $(TARGET_OUT) …
    

    There exists an alternative approach, which does not use 'recursive' linking. But it involves iterations. First, try to build your shared library the usual way. When this fails with unresolved symbols, copy all these symbols to clipboard, and paste them your Android.mk. Let's say these symbols are extBa, extBb, and extBc (in the above scenario, I believe that some object of libC does not find these symbols that are defined somewhere in libB, that's why the link fails). What you need now, add

    LOCAL_LDFLAGS += -Wl,-u'extBa' -Wl,-u'extBb' -Wl,-u'extBc'
    

    You can make the next step, and have this all bundled with libC:

    LOCAL_EXPORT_LDFLAGS += -Wl,-u'extBa' -Wl,-u'extBb' -Wl,-u'extBc'
    

    Now any shared lib that uses libC will not miss these symbols.

    0 讨论(0)
提交回复
热议问题