recipe № D001

Debugging JNI with CLion

In this recipe I will show you how to debug JNI code with CLion application

CLion*

We will do following:

– compile application
– create CLion project with JNI code
– start Java application that uses JNI
– attach to running JVM from CLion
– debug JNI function called from Java

First of all, let’s take a look at recipe directory layout. We will end up with the structure that follows:

What we need to run sample is a simple Java application that will call JNI code. In our case, recipeNoD001.HelloWorld class will work perfectly. The code is super simple. It will call native method displayMessage(int value) 1K times.

We can compile this class with following commands

You can also simply type in the terminal

After class is ready, and we have header file with function signature, we can create C code and CMakeList.txt file.

In CMakeList.txt we want to make sure that:

– we use includes from JAVA (they are needed to compile code)
– we are creating shared library inside project tree
– we are creating shared library instead of executable

Now, you can either create CLion project from the File -> New Project … or you can simply open project that is attached to recipe by choosing File -> Open and navigating to recipeNoD001/c.

open

After you open/create project you should be able to see following structure of project

project

Whole project consists of three files: CMakeList.txt, recipeNoD001_HelloWorld.c, and recipeNoD001_HelloWorld.h

clion_c

Before we proceed with debugging, make sure to compile everything and to build shared library. You can easily do it with:

In order to debug JNI code in CLion we have to make sure to attach to running JVM process that will call JNI function. It is now possible to use Attach to Local Process option from Run menu. This way, you can easily connect to running JVM process and debug code directly within CLion (click the image to watch animated GIF).

clion

That’s it! Isn’t that simple ?!