Search code examples
androidgccrandomglibcbionic

rand() function Bionic vs glibc


I found that rand() function from bionic does't work without including stdlib.h

extern int rand(void);

static void foo()
{
    int a = rand();
}

int main()
{
  foo()
  return 0;
}

Results for glibc:
Compilation successful

Results for bionic:
Compilation unsuccessful

error: undefined reference to 'rand'    

In bionic sources we have following implementation:

static __inline__ int rand(void) {
    return (int)lrand48();
}

Why it works for glibc but not for bionic


Solution

  • glibc's rand() is a "normal" function located in a library. I suspect you're getting a warning about the symbol not being defined from the compiler (which cannot find it), but since the function exists in a library, the link stage can still find and link to it.

    bionic's rand() is a static inline in your header file, that means it's not even defined unless the header file is included. Since the compiler cannot find it without the include and it does not exist in any library that the linker can resolve it from, compilation will fail at the linking stage.