/***********************main.c的內容**************************/
#include<stdio.h>
#include<dlfcn.h>
int main()
{
int a,b;
void *pHandle;
typedef int (*func)(int,int); //注意函數的定義,這里要根據下面的max函數格式定義。
scanf("%d%d",&a,&b);
pHandle=dlopen("./dl2.so",RTLD_NOW);
if (!pHandle)
{
cerr << "Cannot open library: " << dlerror() << ' ';
return 1;
}
func=(func)dlsym(pHandle,"max");
const char *dlsym_error = dlerror();
if (dlsym_error) {
cerr << "Cannot load symbol 'baidu': " << dlsym_error <<' ';
dlclose(pHandle);
return 1;
}
printf("%d與%d相比,%d為大數。\n",a,b,(*func)(a,b));
dlclose(pHandle);
}
/***********************main.c的內容**************************/
/***********************testmax.c的內容**************************/
#include<stdio.h>
int max(int x,int y)
{
return x>y?x:y;
}
/***********************testmax.c的內容**************************/
編譯:
gcc testmax.c -shared -fPIC -o testmax.so
gcc -o main -ldl main.c
運行:
admin@admin-desktop:/abc/test$ ./main
2008 2012
2008與2012相比,2012為大數。