Search code examples
javacgccjava-native-interface

gcc error when compiling the dll for a simple basic program using JNI


This was working a while ago and, I don't really know what happened, but now it isn't working anymore.

It's a simple basic program using JNI.
It has 6 classes:

MainJNI

public class MainJNI {
    static {
        System.loadLibrary("W36Lib");
    }

    public static void main(String[] args) {
        double x = 7.0;
        double y =2.0;
        double sumResult = NativeMethods.sum(x, y);

        System.out.println("Sum = " + sumResult);
    }
}

NativeMethods.java

public class NativeMethods {
    public static native double sum(double x, double y);
}

NativeMethods.c

#include "NativeMethods.h"
#include "legacy.h"
#include <stdio.h>

JNIEXPORT jdouble JNICALL Java_NativeMethods_sum
    (JNIEnv *env, jclass cls, jdouble x, jdouble y) {
    return dSum(x, y);
}

NativeMethods.h - generated with cygwin by the command "javah NativeMethods"

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class NativeMethods */

#ifndef _Included_NativeMethods
#define _Included_NativeMethods
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     NativeMethods
 * Method:    sum
 * Signature: (DD)D
 */
JNIEXPORT jdouble JNICALL Java_NativeMethods_sum
  (JNIEnv *, jclass, jdouble, jdouble);

#ifdef __cplusplus
}
#endif
#endif

legacy.c

#include "legacy.h"

double dSum(double x, double y) {
    double result = x + y;
    return result;
}

legacy.h

double dSum(double x, double y);

This program is supposed to calculate the sum of 2 numbers. Something easy. But when I try to compile in cygwin the .dll of the program by this command:

    gcc -Wl,--add-stdcall-alias -mno-cygwin -shared 
-I"/cygdrive/c/jdk1.7.0_09/include" 
-I"/cygdrive/c/jdk1.7.0_09/include/win32" -o W36Lib.dll NativeMethods.c

(the command is split into 3 rows but it's actually one line. It's split just to look good here)

I have to tell you now that this command was working perfectly a couple of days ago. I don't what happened, but after sending it, I'm receiving this error:

/tmp/ccOvXYYS.o:NativeMethods.c:(.text+0x14): undefined reference to `_dSum'
collect2: ld returned 1 exit status

I really don't know what's wrong and why I'm receiving this error.


Solution

  • You forgot to include legacy.c in compile:

    gcc -Wl,--add-stdcall-alias -mno-cygwin -shared 
    -I"/cygdrive/c/jdk1.7.0_09/include" 
    -I"/cygdrive/c/jdk1.7.0_09/include/win32" -o W36Lib.dll NativeMethods.c legacy.c