//foo.c
#include<stdio.h>
int pen(int a)
{
printf("%d",a);
}
$cc -c foo.c
$ls -shared -o libfoo.so foo.o
///////////now libfoo.so formed
//i have already designed libfoo.so
//main.c
#include<stdio.h>
#include <dlfcn.h>
int main()
{
int (*p)(int)=NULL ;
void *handle;
handle=dlopen("libfoo.so",RTLD_LAZY);
p=dlsym(handle,"pen");
(*p)(5);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
but this gives error
$ cc main.c -ldl
$ ./a.out
Segmentation fault
You have no error checking, for starters. This will tell you where things go wrong.
#include<stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
int main()
{
int (*p)(int)=NULL ;
void *handle;
handle=dlopen("libfoo.so",RTLD_LAZY);
if (!handle)
{
fputs (dlerror(), stderr);
exit(1);
}
p=dlsym(handle,"pen");
{
char *err=dlerror();
if(err!=NULL)
{
fputs(err,stderr);
exit(1);
}
}
(*p)(5);
return 0;
}
In addition to error checking you need to cast the operands and function return values to the proper type before assignment. Source code changes highlighted in red.
#include <stdio.h>
#include <dlfcn.h>
int main(void)
{
int (*p)(int)=NULL;
int i;
void *handle;
handle=dlopen("libfoo.so",RTLD_LAZY);
/* cast the return value from dlsym() to the proper type before assignment to p
p is a pointer to a function that takes an int argument and return an int */
p=((int) (*)(int)) dlsym(handle,"pen");
/* capture the integer return value from the shared library */
i = (*p)(5);
return 0;
}