首页 > 解决方案 > ld -shared success but got a segmentation fault when run

问题描述

I'm a beginner to learn the basic compiling. I create a very simple c file as below

#include <stdio.h>

int main (void) {
  printf("Hello World!\n");
  return 0;
}

then I run the commands,

cpp -E helloworld.c -o helloworld.i
gcc -S helloworld.i -o helloworld.s
as helloworld.s -o helloworld.o
ld -shared -o helloworld /usr/lib64/libc.so helloworld.o

in here, I got an error message like this,

ld -shared -o helloworld /usr/lib64/libc.so helloworld.o
ld: helloworld.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
ld: final link failed: Nonrepresentable section on output

so I rerun the upper but with a -fPIC

cpp -E helloworld.c -o helloworld.i
gcc -S helloworld.i -o helloworld.s -fPIC
as helloworld.s -o helloworld.o
ld -shared -o helloworld /usr/lib64/libc.so helloworld.o

at last, I got my helloworld, but when I try ./helloworld, I got a Segmentation fault.

anyone can help? Thanks in advance!

标签: linuxgccld

解决方案


我试试 gcc helloworld.c -Wl,--verbose | grep 成功并获得如下输出,

attempt to open /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o succeeded
attempt to open /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crti.o succeeded
attempt to open /usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtbegin.o succeeded
attempt to open /tmp/ccSuIvy2.o succeeded
attempt to open /usr/lib/gcc/x86_64-redhat-linux/4.8.5/libgcc.a succeeded
attempt to open /usr/lib/gcc/x86_64-redhat-linux/4.8.5/libgcc_s.so succeeded
attempt to open /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/libc.so succeeded
attempt to open /lib64/libc.so.6 succeeded
attempt to open /usr/lib64/libc_nonshared.a succeeded
attempt to open /lib64/ld-linux-x86-64.so.2 succeeded
attempt to open /usr/lib/gcc/x86_64-redhat-linux/4.8.5/libgcc.a succeeded
attempt to open /usr/lib/gcc/x86_64-redhat-linux/4.8.5/libgcc_s.so succeeded
attempt to open /usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtend.o succeeded
attempt to open /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crtn.o succeeded

但是我还是不知道怎么做链接,我试试这个

ld -shared -o helloworld /usr/lib64/libc.so /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crti.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/libgcc_s.so /usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtend.o /usr/lib64/crtn.o helloworld.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/libgcc.a /usr/lib64/libc_nonshared.a /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o 

但收到错误消息,

ld: /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o: relocation R_X86_64_32S against undefined symbol `__libc_csu_fini' can not be used when making a shared object; recompile with -fPIC
ld: final link failed: Nonrepresentable section on output

推荐阅读