sem_open() 错误:Linux 上的“未定义对 sem_open() 的引用”(Ubuntu 10.10)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4916881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 02:45:06  来源:igfitidea点击:

sem_open() error: "undefined reference to sem_open()" on linux (Ubuntu 10.10)

c++linuxsemaphore

提问by Robin

So I am getting the error: "undefined reference to sem_open()" even though I have include the semaphore.h header. The same thing is happening for all my pthread function calls (mutex, pthread_create, etc). Any thoughts? I am using the following command to compile:

所以我收到错误:“未定义对 sem_open() 的引用”,即使我已经包含了 semaphore.h 标头。我所有的 pthread 函数调用(互斥锁、pthread_create 等)都发生了同样的事情。有什么想法吗?我正在使用以下命令进行编译:

g++ '/home/robin/Desktop/main.cpp' -o '/home/robin/Desktop/main.out'

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

采纳答案by Vlad H

You need link with pthread lib, using -lpthreadoption.

您需要使用-lpthread选项与 pthread 库链接。

回答by William Pursell

Including the header does not tell ld about the library. You need to add -lrt to your compilation command line. For threading, you need either -lpthread or -pthread, depending on your platform.

包含标题不会告诉 ld 有关库的信息。您需要将 -lrt 添加到编译命令行。对于线程,您需要 -lpthread 或 -pthread,具体取决于您的平台。

The library is not the header. The header is not the library. This is an important distinction. See What's the difference between a header file and a library?

图书馆不是标题。标题不是库。这是一个重要的区别。请参阅头文件和库之间的区别是什么?

回答by Sanjay Bhosale

The working option in Ubuntu is -lpthread. But if you work on suse or other systems the correct option is -lrt. Also the book Linux Programmin Interfacementions -lrtas the correct option.

Ubuntu 中的工作选项是-lpthread。但是,如果您在 suse 或其他系统上工作,则正确的选项是-lrt。此外,Linux Programmin Interface一书提到-lrt作为正确选项。