Learn Java

Step 5: Compile native code into shared library

Use below command to compile the C code,

gcc -o libHelloImpl.jnilib -lc -shared \
        -I/System/Library/Frameworks/JavaVM.framework/Headers

and the directory tree is like below.

├── Hello.c
├── classes
│   └── com
│       └── marakana
│           └── jniexamples
│               └── Hello.class
├── com_marakana_jniexamples_Hello.h
├── libHelloImpl.jnilib
└── src
    └── com
        └── marakana
            └── jniexamples
                └── Hello.java

Notes:

The output file extension should be

  • .so: Linux
  • .dll: Windows
  • .jnilib: Mac OS
  • The output file name should be started with lib for Mac.

The flags use to compile and link C code:

  • -shared: -shared

    Produce a shared object which can then be linked with other objects to form an executable. Not all systems support this option. For predictable results, you must also specify the same set of options used for compilation (-fpic, -fPIC, or model suboptions) when you specify this linker option.

  • -lx:

    This option tells the linker to search for libx.dylib or libx.a in the library search path. If string x is of the form y.o, then that file is searched for in the same places, but without prepending lib or appending .a or .dylib to the filename.

    It will find libc.dylib, located in /usr/lib/.