2011-11-15 38 views
4

我正在使用JavaSE-1.6在Suse Linux 11上编写Java程序,并且使用javac构建问题。如何从Linux上的Java代码调用C函数

我下面就

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

教程,迄今已写了下面的:

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); 
    } 
} 

当我运行javac CTest.java我得到一个错误:

/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 

我怀疑它是使用gcc而不是Java版本的javac,但我不确定。

任何想法可能是什么问题?

我已经用在这里提到的“ - 主=”选项尝试:

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

但不是错误之前我刚才得到:

/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 

回答

0

我想你应该安装和使用Sun Java SDK而不是使用gcc javac编译器。

Google对于suse javac gcc抛出了类似问题的负载,并且解决方案似乎总是使用Sun JDK。

+0

谢谢,事实证明我的JDK已经搞乱了,现在我重新安装了它,路径已经修复,我可以运行javac而没有任何问题,现在javah已经正确创建了我的头文件。 –

1

我建议你运行which javac来确定你使用的编译器。如果你想要Java 6,你不能使用gcj。您需要修改你的路径来让你使用从JDK 6

2

一个javac从您引用的页面:

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.

我的重点。你有没有为你的系统设置LD_LIBRARY_PATH(或其他适合的)?

+0

谢谢,事实证明我的JDK已经搞乱了,现在我重新安装了它,路径已经修复,我可以运行javac而没有任何问题,现在javah已经正确创建了我的头文件。 –