Poo*_*rna 2 gcc dynamic-linking
我是linux的新手,在使用动态库进行编译时,我收到了segmentationfault错误.
我有两个文件
ctest1.c
void ctest1(int *i)
{
*i =10;
}
Run Code Online (Sandbox Code Playgroud)
ctest2.c
void ctest2(int *i)
{
*i =20;
}
Run Code Online (Sandbox Code Playgroud)
我已使用以下命令将这两个文件编译到名为libtest.so的共享库中
gcc -shared -W1,-soname,libtest.so.1 -o libtest.so.1.0.1 ctest1.o ctest2.o -lc
Run Code Online (Sandbox Code Playgroud)
我已经编写了另一个程序prog.c,它使用了这个库导出的函数
prog.c中
#include <stdio.h>
void (*ctest1)(int*);
void (ctest2)(int*);
int main()
{
int a;
ctest1(&a);
printf("%d",a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我使用以下命令构建可执行文件时
gcc -Wall prog.c -L.-o prog
但是当我运行生成的可执行文件时,我得到了SegmentationFault错误.
当我用ldd检查prog的标题时,它显示出来
linux-vdso.so.1 =>(0x00007f99dff000)libc.so.6 => /lib64/libc.so.6(0x0007feeaa8c1000)/lib64/ld-linux-x86-64.so.2(0x00007feeaac1c000)
有人可以说出问题所在
你没有调用ctest1.c或ctest2.c.相反,你在prog.c中创建ctest1和ctest2函数指针,你没有初始化,所以当你试图调用它时会导致分段错误.
您需要声明您的函数,以便prog.c可以看到它们,然后将prog.c链接到库(可能使用gcc的-l选项).
#include <stdio.h>
extern void ctest1(int*);
extern void ctest2(int*);
int main()
{
int a;
ctest1(&a);
printf("%d",a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
类似的东西:
gcc -Wall -L. -ltest prog.c -o prog
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
981 次 |
| 最近记录: |