-lrt問題,即:shm_open的標頭檔案存在,編譯卻不通過,提示undefined
C programming in the UNIX environment的程式設計手冊,一般都會為程序間用共享記憶體的方法通訊提供兩組方法:
1. POSIX定義的:
int shm_open(const char *name, int oflag, mode_t mode);
int shm_unlink(const char *name);
int ftruncate(int fd, off_t length);
2. SYSTEM V定義的
int shmget(key_t key, int size, int shmflg);
void *shmat(int shmid, const void *shmaddr, int shmflg);
int shmdt(const void *shmaddr);
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
由於POSIX標準比較通用,一般建議使用該標準定義的方法集。
但是在使用shm_open和shm_unlink兩個函式時,你可能遇到和我同樣的問題,見如下程式碼。
該程式碼旨在測試你的系統是否支援POSIX定義的共享記憶體函式集。
/* This is just to test if the function is found in the libs. */
#include <stdio.h>
#include
#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);
}
假設它所在的檔案為"test.c"
我這麼編譯:
gcc -o test test.c
結果為:
/tmp/ccaGhdRt.o(.text+0x23): In function `main':
: undefined reference to `shm_open'
/tmp/ccaGhdRt.o(.text+0x49): In function `main':
: undefined reference to `shm_unlink'
collect2: ld returned 1 exit status
編譯結果實際上是說,沒include相應的標頭檔案,或是標頭檔案不存在(即系統不支援該庫函式)
但我man shm_open是可以找到幫助檔案的(說明系統支援),原因何在???
請注意一下man shm_open的幫助檔案的最後幾行:
NOTES
These functions are provided in glibc 2.2 and later. Programs using
these functions must specify the -lrt flag to cc in order to link
against the required ("realtime") library.
POSIX leaves the behavior of the combination of O_RDONLY and O_TRUNC
unspecified. On Linux, this will successfully truncate an existing
shared memory object - this may not be so on other Unices.
The POSIX shared memory object implementation on Linux 2.4 makes use of
a dedicated file system, which is normally mounted under /dev/shm.
如果你注意到的話,這樣編譯就能通過了:
gcc -lrt -o test test.c
其實就是要連線庫的原因。