2016-04-07 22 views
2

Ich versuche, den Beispiel-Code zu kompilieren, die APIs von libdl Bibliothek ist:Wie ein Programm mit statischer Bibliothek libdl.a kompilieren

#include <stdio.h> 
#include <stdlib.h> 
#include <dlfcn.h> 

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); 
} 

ich den folgenden Befehl zum Kompilieren verwendet: -> gcc -static -o foo foo.c -ldl

ich habe die folgende Fehlermeldung:

foo.c:(.text+0x1a): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking 

Nachdem google, da ich es statisch zu kompilieren versuche, kann ich die libdl.a in der lib dire finden ctory. Ich bekomme das gleiche Problem mit Gethostbyname API auch. Was sind die anderen Bibliotheken müssen hinzufügen, um dl_open statisch zu kompilieren.

Antwort

0

Ein mögliches Problem:

dlsym() 

Sollte erklärt oder umgesetzt werden, bevor es in main() verwiesen wird.

+0

das war Tippfehler. Ich habe die libdl während der Kompilierung eingefügt. gcc -static -o foo foo.c -ldl –

+0

Wenn jemand eine Idee hat, bitte helfen. –

0

dlopen() funktioniert nur mit freigegebenen Bibliotheken. Das bedeutet, dass Sie es nicht statisch verknüpfen können. Hast du es ohne -static versucht?

+0

Ja, es funktioniert gut ohne -static. Warum können wir nicht mit -static kompilieren? –