简体   繁体   中英

How do I call C functions from Java code on Linux

I am writing a Java program on Suse Linux 11 using JavaSE-1.6 and I am having a problem building using javac.

I am following the tutorial on

http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html

and have so far written the following:

package com.ctest;

class CTest
{
    // Native method declaration
    native int testCall();

    // Load the library
    static
    {
        System.loadLibrary("fpdpReaderLib");
    }

    public static void main(String args[])
    {
        int retVal;

        // Create class instance
        CTest cLangTest = new CTest();

        // Call native method
        retVal = cLangTest.testCall();

        System.out.println(retVal);
    }
}

When I run javac CTest.java i get an error:

/usr/lib/gcc/i586-suse-linux/4.3/../../../crt1.o: in function '_start':
/usr/src/packages/BUILD/glibc-2.9/csu/../sysdeps/i386/elf/start.S:115: undefined reference to 'main'
/tmp/cc97kcJu.o:(.data+0x28) undefined reference to 'hidden alias for int com::ctest::CTest::testCall()'
/tmp/cc97kcJu.o:(.data+0x74) undefined reference to 'hidden alias for int com::ctest::CTest::testCall()'
collect2: ld returned 1 exit status

I am suspecting it is using gcc rather than the java version of javac but I'm not sure.

Any ideas what the problem could be?

I have tried using the "--main=" option mentioned here:

http://gcc.gnu.org/java/faq.html#4_1

but instead of the error before I now just get:

/tmp/ccwfugWq.o:(.data+0x28) undefined reference to 'hidden alias for int com::ctest::CTest::testCall()'
/tmp/ccwfugWq.o:(.data+0x74) undefined reference to 'hidden alias for int com::ctest::CTest::testCall()'
collect2: ld returned 1 exit status

From the page that you cited:

The library containing the native code implementation is loaded by a call to System.loadLibrary(). Placing this call in a static initializer ensures this library is only loaded once per class. The library can be loaded outside of the static block if your application requires it. You might need to configure your environment so the loadLibrary method can find your native code library.

My emphasis. Have you set the LD_LIBRARY_PATH (or whatever is appropriate) for your system?

I suggest you run which javac to determine which compiler you are using. If you want Java 6, you can't use gcj. You need to fix you PATH so you have using a javac from JDK 6.

I think you should install and use the Sun Java SDK rather than using the gcc javac compiler.

Google for suse javac gcc throws up loads of similar problems and the solution always seems to be to use the Sun JDK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM