2012-03-29 13 views
24

Ho appena un crash del sistema e reinstallare Ubuntu 11.10, e il mio codice produce questo strano errore.riferimento undefined 'shm_open', già aggiunto flag -lrt qui

Ho scritto un esempio di codice semplice per testare dove il problema è:

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <fcntl.h> 
#include <sys/mman.h> 
#include <sys/stat.h> 

int main (void) { 

    int i; 

    i = shm_open ("/tmp/shared", O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); printf ("shm_open rc = %d\n", i); 

    shm_unlink ("/tmp/shared"); 

    return (0); 
} 

e il comando di compilazione è

gcc -lrt test.c -o test

L'errore è:

/tmp/ccxVIUiP.o: In function `main': 
test.c:(.text+0x21): undefined reference to `shm_open' 
test.c:(.text+0x46): undefined reference to `shm_unlink' 
collect2: ld returned 1 exit status 

I ho già aggiunto -lrt lib, perché non si compila ancora?

+0

Penso che si potrebbe voler -pthread, ma ho dimenticato? le ragioni. – blueshift

+0

grazie, il computer del mio mentore deve aggiungere -pthread, è una versione migliorata di lpthread con funzioni thread safe. e potrei semplicemente aggiungere lrt. Penso che sia lrt che pthread siano le librerie di POSIX? – bxshi

+0

@bxshi: POSIX non specifica i nomi delle librerie; i vari sapori di Unix hanno funzioni in librerie con nomi diversi. –

risposta

40

librerie alla fine:

gcc test.c -o prova -lrt

Da GCC Link Options:

 
-llibrary 
-l library 
    Search the library named library when linking. 
    (The second alternative with the library as a separate argument 
    is only for POSIX compliance and is not recommended.) 

    It makes a difference where in the command you write this option; 
    the linker searches and processes libraries and object files in the 
    order they are specified. 
    Thus, `foo.o -lz bar.o' searches library `z' after file foo.o but 
    before bar.o. If bar.o refers to functions in `z', those functions 
    may not be loaded. 
+1

Suppongo che l'aggiunta di librerie da qualche parte nel mezzo funzioni anche. Solo curioso perché 'gcc' considera l'ordine così importante? –

+0

Ero così stupido ... Grazie. – bxshi

+1

Questa volta ho bisogno di aggiungere lib alla fine di questo comando gcc, ma prima di reinstallare il mio linux, potrei aggiungere lib subito dopo 'gcc' e potrebbe anche compilare. Come va? C'è qualche file di configurazione o variabile su questo? – bxshi

3

Modificare la riga di compilazione da

gcc -lrt test.c -o test 

per

gcc test.c -o test -lrt 
+0

gcc ha sempre bisogno di aggiungere lib alla fine?Non ho modificato il mio codice e Makefile, ma prima di reinstallare il mio computer, funziona perfettamente. – bxshi

4

In Expert C programming Pagina 108: <Handy Heuristic> Where to Put Library Options:Always put the -l library options at the rightmost end of your compilation command line. Ma non dice il motivo per cui, quindi credo che questo è un po 'una regola :)

Problemi correlati