Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Quick links: redhat.com, Customer Portal, Red Hat's developer site, Red Hat's partner site.

  • You are here

    Red Hat

    Learn about our open source products, services, and company.

  • You are here

    Red Hat Customer Portal

    Get product support and knowledge from the open source experts.

  • You are here

    Red Hat Developer

    Read developer tutorials and download Red Hat software for cloud application development.

  • You are here

    Red Hat Partner Connect

    Get training, subscriptions, certifications, and more for partners to build, sell, and support customer solutions.

Products & tools

  • Ansible.com

    Learn about and try our IT automation product.
  • Red Hat Ecosystem Catalog

    Find hardware, software, and cloud providers―and download container images―certified to perform with Red Hat technologies.

Try, buy, & sell

  • Red Hat Hybrid Cloud Console

    Access technical how-tos, tutorials, and learning paths focused on Red Hat’s hybrid cloud managed services.
  • Red Hat Store

    Buy select Red Hat products and services online.
  • Red Hat Marketplace

    Try, buy, sell, and manage certified enterprise software for container-based environments.

Events

  • Red Hat Summit and AnsibleFest

    Register for and learn about our annual open source IT industry event.

Eclipse for JNI development and debugging on Linux (Java and C)

November 3, 2016
Leo Ufimtsev
Related topics:
Developer ToolsJava
Related products:
Developer Tools

Share:

Share on twitter Share on facebook Share on linkedin Share with email
  • Cross language development in one project
  • Introduction
  • Quick start
  • General overview of JNI compilation and the Eclipse project
  • Code navigation and Java/C project nature
  • Debugging Java and C
  •  
  • Checking native code with -Xcheck:jni
  • Misc notes
  • Further Readings
Cross language development in one project

selection_166Cross language development in one project

In this tutorial style article I'll discuss how to configure Eclipse for Java Native Interface (JNI) development based on a sample project that you can copy and modify. I.e, you can have a single project that can be both Java and C at the same time, and support a full code navigation and debugging of both languages.

This article is focused on the configuration of Eclipse rather than explaining JNI itself, however there are links to JNI literature at the end.

Introduction

Introduction

JNI is useful in many situations, for example if your Java applications needs to interface with a native C library. An example of this is Eclipse's own interface, which on Linux is drawn by a native C library "GTK", thus the native Linux look. Further, sometimes you may have custom  'C' code in your Java applications. Developing, and especially debugging this custom code can be difficult and cumbersome, but it doesn't have to.

In this tutorial I will provide a sample project that I glued together based on various tutorials (see further readings) and explain each of the components. This combined with the JNI literature and other tutorials listed at the bottom of this article should help you getting started with JNI development.

Please post comments if you have questions/feedback.

I shall assume you have some familiarity with the following:

  • Java
  • C
  • GCC (Tutorial)
  • makefiles  (Tutorial 1, Tutorial 2, Tutorial 3, and quick reference)
  • You don't need to have  JNI knowledge as this project can be used to learn about JNI, but reading introduction chapters 1 and 2 from the book first would help you a lot.
  • Eclipse basics
    • Eclipse for Java development (Tutorial)
    • Eclipse for C development (See 'getting started' from User Guide)

You require the following packages for JNI development:

  • Java Development tools (JDK as oppose to JRE)
    • dnf install java-1.8.0-openjdk.x86_64
    • dnf install java-1.8.0-openjdk-devel.x86_64    # contains jni.h
    • dnf install java-1.8.0-openjdk-src.x86_64  # useful to view Java source code
    • dnf install java-1.8.0-openjdk-debuginfo.x86_64  # for C debugging.
  • C Development tools
    • dnf install groups install "C Development Tools and Libraries"
  • Eclipse with C and Java
    • Eclipse comes in packages designed for certain languages. But you can add additional languages via plugin installation.
    • You can install the "Eclipse for Java development" and from the market place install the "CDT" plugin (Tutorial).
Quick start

Quick start

You can download sample project (or follow newest master),  import it into your Eclipse and do the following:

  • In the "jni" folder, you should see 'C' "Build Targets". Run "all",
    selection_169
    or from the command line:

     

    cd jni
    make all
    Copy snippet
  • This should produce HelloJNI.h and libhello.so
  • in the 'Src' java package, right click on HelloJNI.java and click on "Run as -> Java application" (You will see an error in the console saying "java.lang.UnsatisfiedLinkError: no hello in java.library.path...")
  • Edit the newly created run configuration (Run -> Run Configurations -> HelloJNI), go to "Arguments tab and under "VM arguments" add: -Djava.library.path=jni
    selection_168
  • Now run this configuration and you should see the following in your console:
    Java: Hello world.
    c: Hello World!
    Copy snippet

You may note, this project is both a 'Java' and a 'C' project.

General overview of JNI compilation and the Eclipse project

General overview of JNI compilation and the Eclipse project

The following diagram illustrates what is going when you compile and run your JNI project:

selection_167Note:

  • There are two compile cycles. In the first compile your Java source code is parsed for the 'native' keyword and a '.h' header file is generated by javah (Java header compiler).
  • Subsequently the header file is combined with your C source code (and the jni.h from the system) to produce an objective file and a shared library (libhello.so).
  • The .h header file contains the glue code between Java and your C file. So when you add java native methods, you need to re-generate your header first (HelloJNI.h makefile target), then use the function prototype in your C file.
  • However, the makefile target 'all' does both in one step if you didn't add any extra native calls in Java.

The project layout has the following files:

selection_170

If the above doesn't make any sense, read chapters 1 and 2 from the book.

Note the following about this project:

  • Eclipse compiles .java '.class' files into ./bin. To compensate, the makefile defines a CLASS_PATH variable (../bin), which is used by vpath and javah.
  • To run a Java file, the run time configuration of the Java file has to be updated. In the "VM arguments", we add "-Djava.library.path=jni"so that Java can find the '.so' library. (See quick start)
  • The compilation of the .c/.h files adds the include paths to jni.h and jni_md.h:
    gcc $(CFLAGS) -fPIC -I/usr/lib/jvm/java/include -I/usr/lib/jvm/java/include/linux
    Copy snippet

    These may vary slightly if you installed your Java in some other location.

  • The makefile adds "DEBUGFLAGS" so that you can debug the 'C' part of your code.
Code navigation and Java/C project nature

Code navigation and Java/C project nature

By opening up HelloJNI.java and HelloJNI.c, you should be able to navigate code the way you can normally navigate through java/c files in Eclipse. I.e open declarations and things like that. The reason is that the Java project has an added "C/C++" nature, so that it understands both languages.

Normally, this can be accomplished by creating a java project, then right clicking on it -> New -> Other -> Convert to a C/C++ Project (Adds C/C++ Nature) -> next.
In the dialog, in Project type, select "Makefile Project" -> in Toolchains, select "Linux GCC"
selection_182

selection_183

A note on perspectives

When I do Java development, I switch to the Java perspective. When I work on C, I switch to the C perspective.

selection_184

The perspectives display certain features, for example the C perspective typically switches to the "Project Explorer", which will display the build targets:

selection_185

Where as in Java you typically view the "Package Explorer" which doesn't show the make targets.

I tried these two to hot keys: Alt+j and Alt+c in the keyboard shortcut preferences. (Show Perspective (...))

Debugging Java and C

Debugging Java and C

Debugging the C part is a two step procedure.

  • To debug the Java part, launch with standard Java debugger:
    selection_172
  • To debug the C part, you should ideally pause somewhere in Java and then attach the CDT debugger to the Java process. After that CDT will break on breakpoints in the C code.

You can do so as following:

  • Set a breakpoint in the Java code before a JNI call.
  • Set a breakpoint in the C code:
    selection_171
  • Run HelloJNI.java in debug. It should break somewhere before the JNI call. The sample project should have printed the PID of the process. Make a note of the PID:
    selection_174
    Alternatively, you can use the command line utility "jps" (java process) to list the PID of Java processes:
    selection_175
  • From the Quick Access entry (Ctrl+3), search for "Debug Attached Executable":
    selection_173
  • You will be asked to select a process. Type "Java" and select the one with the PID noted above
    selection_176
  • By now you should be in the debug perspective. You will see two entries in the Debug view. The debugger attached to the thread of the JVM, but it hasn't stopped at the "C" breakpoint just yet. Click on pthread_join() and then on continue.
    selection_178
  • Next click on "HelloJNI.main" from the Java entry. Now you can continue here also. Now CDT should break in the C process.
    You can now step through the C part of the JNI program, inspect variable content etc..
    selection_179

Switching between Java and GDB consoles

You may notice that your Java console dissapeared and instead the GDB console showed up. (Btw, you can type GDB commands into it).

To switch between them, click on this button:

selection_180

 

 

Checking native code with -Xcheck:jni

Checking native code with -Xcheck:jni

It's sometimes easy to make subtle mistakes in your JNI code. For example forget to check for exceptions after calling a JNI function from your C code.

In  C, gcc has a flag "-Wall", which prints all warnings when compiling. JVM has something similar. You can add the "-Xcheck:jni" vm argument to your run-time configuration and Java will print additional runtime errors when it thinks you forgot to do something.

Adding -Xcheck:jni to run configuration:

Selection_230.png

 

As an example, if you run the following native code without checking if an exception occurred after doing so, you will get a warning in the Java console when you run the snippet:

JNIEXPORT void JNICALL Java_HelloJNI_cCallingJava (JNIEnv *env, jobject thisObj) {
....
(*env)->CallVoidMethod(env,thisObj, javaMethod, 3);
.... // we forgot to check for exceptions here...
}
Copy snippet

 

 

Error in console  when running snippet (not compiling):
Selection_231.png

The fix in this case is to check for an error:

JNIEXPORT void JNICALL Java_HelloJNI_cCallingJava (JNIEnv *env, jobject thisObj) {
....
(*env)->CallVoidMethod(env,thisObj, javaMethod, 3);
// Check if exception occured:
if ((*env)->ExceptionCheck(env) == JNI_TRUE) {
return;
}
....
}
Copy snippet
Misc notes

Misc notes

Adding includes

You might notice that in HelloJNI.c, when you hover over '<jni.h>' and press F3, you will jump to it's declaration. This works because I added the includes into the project properties manually. "jni.h" by default is not in the system path. I added the includes so that the CDT indexer knows how to find them. Similarly, if you use custom includes for CDT to recognize them, you should add them to the Paths and Symbols in your project.

selection_181

It's also worth reading over jni.h and jni_md.h. These define a lot of the types that you'll be using for JNI development, for example jint and jlong are defined in jni_md.h:

typedef int jint;
typedef long jlong;
typedef signed char jbyte;
Copy snippet

Naming of library files

Note, on Linux, your '.so' file should be named :  libYOURNAME.so ("lib" prefix and ".so" extension), but the loadLibrary function should only say YOURNAME. The reason is cross-platform compatibility as library files on windows have 'dll' and don't have 'lib' prefix.

System.loadLibrary(&quot;hello&quot;);
Copy snippet
libhello.so
Copy snippet
Further Readings

Further Readings

JNI Literature

  • Book: Java Native Interface: Programmer's Guide and Specification"
    This is a very good book on getting started with JNI and also good as a reference.  The first couple of chapters get you going, while the advance chapters go into more rigorous depth. The end is used as a reference.
  • Oracle's JNI documentation

Other Eclipse / JNI tutorials:

  • The following is a good tutorial if you want to create a new JNI project from scratch, as well as JNI basics.
    http://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html

     

    • This extensive Stack overflow post relates to the article above:
      http://stackoverflow.com/questions/23612450/how-to-create-a-makefile-for-jni-configuration-in-linux-and-eclipse
  • The following covers Eclipse JNI setup for a windows machine:
    http://www.bogotobogo.com/cplusplus/eclipse_CDT_JNI_MinGW_64bit.php
Last updated: January 13, 2022

Recent Posts

  • LLM Compressor: Optimize LLMs for low-latency deployments

  • How to set up NVIDIA NIM on Red Hat OpenShift AI

  • Leveraging Ansible Event-Driven Automation for Automatic CPU Scaling in OpenShift Virtualization

  • Python packaging for RHEL 9 & 10 using pyproject RPM macros

  • Kafka Monthly Digest: April 2025

Red Hat Developers logo LinkedIn YouTube Twitter Facebook

Products

  • Red Hat Enterprise Linux
  • Red Hat OpenShift
  • Red Hat Ansible Automation Platform

Build

  • Developer Sandbox
  • Developer Tools
  • Interactive Tutorials
  • API Catalog

Quicklinks

  • Learning Resources
  • E-books
  • Cheat Sheets
  • Blog
  • Events
  • Newsletter

Communicate

  • About us
  • Contact sales
  • Find a partner
  • Report a website issue
  • Site Status Dashboard
  • Report a security problem

RED HAT DEVELOPER

Build here. Go anywhere.

We serve the builders. The problem solvers who create careers with code.

Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

Sign me up

Red Hat legal and privacy links

  • About Red Hat
  • Jobs
  • Events
  • Locations
  • Contact Red Hat
  • Red Hat Blog
  • Inclusion at Red Hat
  • Cool Stuff Store
  • Red Hat Summit

Red Hat legal and privacy links

  • Privacy statement
  • Terms of use
  • All policies and guidelines
  • Digital accessibility

Report a website issue