所以我得到的错误:“未定义的引用sem_open()”即使我已经包括semaphore.h头。 所有我的pthread函数调用(互斥体,pthread_create等)都发生了同样的事情。 有什么想法吗? 我正在使用下面的命令来编译:
g ++'/home/robin/Desktop/main.cpp'-o'/home/robin/Desktop/main.out'
#include <iostream> using namespace std; #include <pthread.h> #include <semaphore.h> #include <fcntl.h> const char *serverControl = "/serverControl"; sem_t* semID; int main ( int argc, char *argv[] ) { //create semaphore used to control servers semID = sem_open(serverControl,O_CREAT,O_RDWR,0); return 0; }
您需要使用-lpthread
选项与pthread lib链接。
包括标题不会告诉ld关于这个库。 您需要将-lrt添加到您的编译命令行。 对于线程,您需要-lpthread或-pthread,具体取决于您的平台。
图书馆不是标题。 标题不是图书馆。 这是一个重要的区别。 看看头文件和库有什么区别?
Ubuntu中的工作选项是-lpthread 。 但是如果你在suse或其他系统上工作,正确的选项是-lrt 。 另外,本书的Linux Programmin Interface提到了–作为正确的选择。