androidc++android-ndkweak-linking

Does Android support weak symbols?


I've been looking at questions like:

It seems to me this could be solved with weak symbols. That is, a native component could provide symbols like rand but adorn them with __attribute__((weak)). If the symbol is found in another library, like the standard runtime, then the weakly linked symbol would not be used. On the other hand, if the symbol was missing, then the native component's version would be used.

I'm having trouble locating information on it for Android (too much unrelated noise while searching).

I opened one of my Crypto++/JNI sample projects and added the following to a CPP file. The AutoSeededRandomPool is just a Crypto++ random number generator object (there's nothing special or tricky below).

// CPP file

#ifdef __cplusplus
extern "C" {
#endif

int __attribute__((weak)) rand(void)
{
    int r;

    AutoSeededRandomPool& prng = GetPRNG();
    prng.GenerateBlock(&r, sizeof(r));

    return r;
}

#ifdef __cplusplus
}
#endif

Trying to compile it results in redefinition of int rand(). I've also tried the following:

// CPP file

#ifdef __cplusplus
extern "C" {
#endif

int rand(void) __attribute__((weak));

int random(void)
{
   ...
}

#ifdef __cplusplus
}
#endif

And moving int rand(void) __attribute__((weak)); to the H file produces the same redefinition of int rand().

And I don't receive any errors or warnings about an unknown attribute.

I also see that __GXX_WEAK__ is defined to 1 in the preprocessor, but SUPPORTS_WEAK is not defined, so its mixed signals (perhaps a bug, similar to Define GXX_WEAK to 0 when using -fno-weak).

I'm not sure if I am doing something wrong, or experiencing something like const and weak attribute with c++ code, or something else.

Does Android support weak symbols? If so, how does one use them.


Here a similar Stack Overflow question that does not have an answer:


Some system details:


Solution

  • Android doesn't support weak symbol override.

    In the recent release android-5.0.2_r1, see the comment at line 539 in linker.cpp source code

    /*
     *
     * Notes on weak symbols:
     * The ELF specs are ambigious about treatment of weak definitions in
     * dynamic linking.  Some systems return the first definition found
     * and some the first non-weak definition.   This is system dependent.
     * Here we return the first definition found for simplicity.
     */
    

    This comment exists from version 2.2_r1 (which is in linker.c) to newest version 5.0.2_r1