Gcc動態連結
函式名稱
dlopen, dlclose, dlerror, dlsym - 動態連結載入器的可程式介面函式
摘要
#include
#include
#include
int
main(int argc, char **argv)
{
void *handle;
double (*cosine)(double);
char *error;
handle = dlopen("libm.so", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
dlerror(); /* Clear any existing error */
/* Writing: cosine = (double (*)(double)) dlsym(handle, "cos");
would seem more natural, but the C99 standard leaves
casting from "void *" to a function pointer undefined.
The assignment used below is the POSIX.1-2003 (Technical
Corrigendum 1) workaround; see the Rationale for the
POSIX specification of dlsym(). */
*(void **) (&cosine) = dlsym(handle, "cos");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", error);
exit(EXIT_FAILURE);
}
printf("%f\n", (*cosine)(2.0));
dlclose(handle);
exit(EXIT_SUCCESS);
}
上述範例程式檔名取名為"foo.c", 讀者可使用下列指令編譯程式:
$ gcc -rdynamic -o foo foo.c -ldl
執行foo程式,結果如下:
$ ./foo
-0.416147
- Jan 04 Wed 2012 18:49
Gcc動態連結
全站熱搜
留言列表