在Linux上如何从Java代码调用C函数
我正在使用JavaSE-1.6在suselinux11上编写一个Java程序,在使用javac构建时遇到了一个问题 我正在学习有关的教程 到目前为止,他们写了以下内容:在Linux上如何从Java代码调用C函数,c,gcc,java-native-interface,java,C,Gcc,Java Native Interface,Java,我正在使用JavaSE-1.6在suselinux11上编写一个Java程序,在使用javac构建时遇到了一个问题 我正在学习有关的教程 到目前为止,他们写了以下内容: package com.ctest; class CTest { // Native method declaration native int testCall(); // Load the library static { System.loadLibrary("
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而不是javac的java版本,但我不确定
你知道问题出在哪里吗
我尝试过使用这里提到的“-main=”选项:
但我现在得到的不是之前的错误:
/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
我认为您应该安装并使用sunjavasdk,而不是使用gccjavac编译器
Google for抛出了大量类似的问题,解决方案似乎总是使用Sun JDK。我建议您运行
which javac
来确定您使用的编译器。如果您想要Java6,就不能使用gcj。您需要修复路径,以便使用JDK 6中的javac
。从您引用的页面:
包含本机代码实现的库由
调用System.loadLibrary()。将此调用置于静态
初始值设定项确保每个类只加载一次此库。这个
如果您的应用程序
需要它您可能需要配置您的环境,以便
loadLibrary方法可以找到本机代码库。
我的重点。您是否为您的系统设置了LD_LIBRARY_路径(或任何合适的路径)?谢谢,原来我的JDK出了问题,现在我已经重新安装了它,路径已经修复,我可以毫无问题地运行javac,javah现在已经正确地创建了我的头文件。谢谢,结果我的JDK被弄糟了,现在我已经重新安装了它,路径已经修复,我可以毫无问题地运行javac,javah现在已经正确地创建了我的头文件。