如何解决“致命:重定位仍然针对可分配但不可写的部分"?在使用Java本机接口时?

2022-01-25 00:00:00 solaris c native java java-native-interface

我正在尝试在 Java 代码中调用 C 函数.我有这个哈瓦代码.

I'm trying to call a C function inside a Java code. I have this hava code.

public class JavaToC {

    public native void helloC();

    static {
        System.loadLibrary("HelloWorld");
    }

    public static void main(String[] args) {
        new JavaToC().helloC();
    }
}

.我编译了它,然后创建了头文件.然后制作下面的 HelloWorld.c 文件.

. I compiled it and then created header file. Then make the following HelloWorld.c file.

#include <stdio.h>
#include <jni.h>
#include "JavaToC.h"
JNIEXPORT void JNICALL Java_JavaToC_helloC(JNIEnv *env, jobject javaobj)
{
  printf("Hello World: From C");
  return;
}

我尝试使用gcc -o libHelloWorld.so -shared -I/usr/java/include -I/usr/java/include/solaris HelloWorld.c -lc"来编译它,但它给出了以下结果.

I tried compiling this using "gcc -o libHelloWorld.so -shared -I/usr/java/include -I/usr/java/include/solaris HelloWorld.c -lc", but it gives the following result.

Text relocation remains                     referenced
    against symbol          offset  in file
.rodata (section)                   0x9         /var/tmp//cc.GaGrd.o
printf                              0xe         /var/tmp//cc.GaGrd.o
ld: fatal: relocations remain against allocatable but non-writable sections
collect2: ld returned 1 exit status

我正在使用 Solaris 11,我该如何解决这个问题?

I'm working on Solaris 11, how can I solve this?

推荐答案

我目前无法在 Solaris 机器上测试这个,但是来自 http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/SPARC-Options.html

I cannot test this on a Solaris machine at the moment, but from http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/SPARC-Options.html

-mimpure-text 抑制重定位仍然针对可分配但不可写的部分"链接器错误消息.但是,那必要的重定位将触发写时复制,并且共享对象实际上并未跨进程共享.而不是使用-mimpure-text,你应该用-fpic-fPIC编译所有源代码.

-mimpure-text suppresses the "relocations remain against allocatable but non-writable sections" linker error message. However, the necessary relocations will trigger copy-on-write, and the shared object is not actually shared across processes. Instead of using -mimpure-text, you should compile all source code with -fpic or -fPIC.

解决方案似乎是添加 -fpic 选项以生成与位置无关的代码.

the solution seems to be to add the -fpic option to generate position-independent code.

相关文章