recipe № D002

Debugging JNI with IntelliJ and CLion

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


We will do following:

– compile C application
– compile Java application
– create CLion project with JNI code
– create IntelliJ project with Java code
– run project in IntelliJ
– 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 (note that we are using exactly the same source code as for recipe № D001):

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.


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


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


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. This time, we will run the project from IntelliJ. First of all, we have to setup the project. That’s fairly easy. Create empty Java project in IntelliJ. Then, add source directory from the sample code inside recipeNoD001/java. Just add it to project’s sources. You should have the structure similar to following one


And your project window should contain just one Java file:


Before you proceed with the execution, there is one more thing you have to do. Java code will use shared library (one that contains JNI code). You have to make sure that Run/Debug configuration (Run -> Edit configurations…) point to the location where shared library is. Take a look below (remember, you can use ${HOME} if you want to refer to location relative to your home directory).


Everything is ready for debugging. This time, however, I will not describe the steps. Instead, enjoy the movie.

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