Search code examples
androidandroid-ndkjava-native-interfacetoolchain

ndk-build NDK_TOOLCHAIN_VERSION 4.8 vs clang


Some time ago I developed a jni wrapper for the C libspeex audio codec. Recently I had some problem in compiling and running this with the ndk r10e, since the audio encode function crashed in runtime.

Finally I found that when I compile with

NDK_TOOLCHAIN_VERSION:=4.8

the native code runs while with

NDK_TOOLCHAIN_VERSION:=clang

it crashes. I wonder about the difference between the two toolchains.

The logcat of the crash:

11-02 14:26:33.642 1908-1908/com.ermes.intau D/dalvikvm: GC_FOR_ALLOC freed 1248K, 20% free 34140K/42456K, paused 102ms, total 102ms
11-02 14:26:33.642 1908-2514/com.ermes.intau A/libc: Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1), thread 2514 (Thread-103909)
11-02 14:26:33.742 1908-1908/com.ermes.intau D/dalvikvm: GC_FOR_ALLOC freed 6K, 18% free 34883K/42456K, paused 89ms, total 89ms

Solution

  • gcc and clang are completely different C compilers. They have no common code.

    Of course they aren't developed in a vacuum. The developers of both compilers do compete with each other to generate the best / fastest machine code. While the optimisations they both perform may be based on the same ideas, they both have different edge cases that will be compiled differently.

    With clang being the newest compiler to be developed, they do try to compile other open source projects that have a history of being compiled by gcc. With either clang or the open source project being changed whenever bugs are found.

    The C language standard also leaves a lot of behaviour undefined. Things like dividing by zero, dereferencing a NULL pointer, signed integer overflows, alignment of stack allocations... Both compilers will exploit these edge cases to generate faster code. If a block of code "might" do something weird, the compiler can assume that the developer knows what they are doing and have handled these cases elsewhere. http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html