I am new to linux, while compiling with dynamic library I am getting the segmentationfault error.
I have two files
ctest1.c
void ctest1(int *i)
{
*i =10;
}
ctest2.c
void ctest2(int *i)
{
*i =20;
}
I have compiled both files to a shared library named libtest.so using following command
gcc -shared -W1,-soname,libtest.so.1 -o libtest.so.1.0.1 ctest1.o ctest2.o -lc
And I have wrote another program prog.c which uses functions exported by this library
prog.c
#include <stdio.h>
void (*ctest1)(int*);
void (ctest2)(int*);
int main()
{
int a;
ctest1(&a);
printf("%d",a);
return 0;
}
And when I have built the executable with following command
gcc -Wall prog.c -L. -o prog
But when I run the generated executable I get the SegmentationFault error.
When I checked the header of prog with ldd it shows
linux-vdso.so.1 => (0x00007f99dff000)
libc.so.6 => /lib64/libc.so.6 (0x0007feeaa8c1000)
/lib64/ld-linux-x86-64.so.2 (0x00007feeaac1c000)
Can somebody tell what is the problem
You aren’t calling into ctest1.c or ctest2.c. Instead, you’re creating ctest1 and ctest2 function pointers in prog.c, which you are not initializing, so it is causing a segmentation fault when you try to call them.
You need to declare your functions so prog.c can see them, and then link prog.c to the libraries (probably using the -l option to gcc).
And something like: