【问题标题】:sem_open() error: "undefined reference to sem_open()" on linux (Ubuntu 10.10)sem_open() 错误:Linux (Ubuntu 10.10) 上的“未定义对 sem_open() 的引用”
【发布时间】:2011-06-22 11:01:41
【问题描述】:

所以我收到错误:“未定义对 sem_open() 的引用”,即使我已经包含了 semaphore.h 标头。我所有的 pthread 函数调用(mutex、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;
}

【问题讨论】:

    标签: c++ linux semaphore


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      库不是标题。标题不是库。这是一个重要的区别。见What's the difference between a header file and a library?

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多