Question

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

Was it helpful?

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.

OTHER TIPS

You will get the answer if you just compare bionic and glibc sources of rand function: https://github.com/android/platform_bionic/blob/master/libc/include/stdlib.h and http://sourceware.org/git/?p=glibc.git;a=blob;f=stdlib/rand.c;hb=glibc-2.15#l26

You can see that in bionic library it inlined in header file so without .h file you can't use it.And in glibc it is separated like most of the functions. The reason is obvious I think - bionic library was developed specially for use in embedded and mobile devices with memory and speed limits, so less code and inline optimizations is useful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top