使用nm查看文件中的符号。
例如代码:
cat sub1.c
-----------------------------------------------
#include <stdlib.h>
int prn1(char *str)
{
printf("This is in sub1.d !!");
printf("%s\n",str);
}
-----------------------------------------------
编译命令:
$cc -c sub1.c (生成sub1.o)
$nm sub1.o
00000000 t gcc2_compiled.
U printf
00000000 T prn1
$ld -G -o sub1.d sub1.o
$nm sub1.d
00001210 A _DYNAMIC
00001204 A _GLOBAL_OFFSET_TABLE_
00001260 A __bss_start
00001260 A _edata
00001260 A _end
000001eb A _etext
000001c8 t gcc2_compiled.
U printf
000001c8 T prn1
调用方代码:
-----------------------------------------------
//#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <unistd.h>
#define __MAIN__
#include "Debug.h"
#undef __MAIN__
#define DEF_DL_FILE "sub1.d"
#define DEF_DL_FUN "prn1"
main(int argc,char *argv[])
{
void *handle;
int (*prn)(char *str);
char *error;
char dlFileName[100],dlFileDir[100],dlFunName[50];
memset(dlFunName,'\0',50);
memset(dlFileDir,'\0',100);
memset(dlFileName,'\0',100);
getcwd(dlFileDir,100);
if ( argc >= 2 )
sprintf(dlFileName,"%s/%s",dlFileDir,argv[1]);
else
sprintf(dlFileName,"%s/%s",dlFileDir,DEF_DL_FILE);
MsgStr(dlFileName);
if ( argc == 3 )
strcpy(dlFunName,argv[2]);
else
strcpy(dlFunName,DEF_DL_FUN);
MsgStr(dlFunName);
handle=dlopen(dlFileName,RTLD_LAZY);
if (!handle)
{
fputs (dlerror(), stderr);
exit(1);
}
Msg("After dlopen()!!");
prn = dlsym(handle, dlFunName);
if ((error = dlerror()) != NULL)
{
fputs(error, stderr);
exit(1);
}
Msg("After dlsym()!!");
prn("Good!!");
Msg("After prn()!!");
dlclose(handle);
Msg("After dlclose()!!");
}
-----------------------------------------------
编译命令:
gcc -c main.c
gcc -o main.x main.o -ldl
-ldl启用动态链接库。
执行效果:
-----------------------------------------------
:: dlFileName is string: /home/Mento/coding/c/dltst/sub1.d
:: dlFunName is string: prn1
:: Message: After dlopen()!!
:: Message: After dlsym()!!
This is in sub1.d !!Good!!
:: Message: After prn()!!
:: Message: After dlclose()!!
-----------------------------------------------