【问题标题】:sem_open doesn't work with Ubuntu : undefined reference to `sem_open'sem_open 不适用于 Ubuntu:未定义对 `sem_open' 的引用
【发布时间】:2012-07-16 08:50:43
【问题描述】:

鉴于此代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <pthread.h>

#define BUF_SIZE 256
int main()
{
    key_t key;
    char *virtualaddr;
    sem_t *get, *put;
    int shmid;

   const char* messageOne = "Hello world , I'm child number 1\n";
   const char* messageTwo = "Hello world , I'm child number 2\n";

   char buf[BUF_SIZE];

   key = ftok("anyfile",'R');

  shmid = shmget(key,1024,0644|IPC_CREAT);
...
...
shmctl (shmid, IPC_RMID, NULL);
exit(EXIT_SUCCESS);
}

我从 eclipse undefined reference to sem_open 得到。

我已经检查了这个post,因为这个问题与我的非常相似,但不明白我的错误在哪里,

您能否解释一下我需要在哪里修复它/添加另一个编译命令(如果确实如此)?

非常感谢

【问题讨论】:

  • 请仔细阅读该问题的第二个答案。你没有做它说你应该做的事情。
  • 我不知道eclipse是怎么工作的,所以这里有个问题:什么时候报错?它是在您输入 sem_open 时显示在编辑器中,还是仅在/编译时显示?你是怎么编译的?
  • @ArjunShankar:只有当我编译它时。

标签: c linux ubuntu pipe shared-memory


【解决方案1】:

编译时需要包含-lpthread。链接器使用它来将二进制文件与库链接。

其他答案已经涵盖了如何在命令行上执行此操作。

要在 Eclipse 中执行此操作,您需要按照指示 here

在项目属性中,转到:C/C++ Build --> Settings。然后 “工具设置”,选择“链接器”下的“库”。您可以添加所有 你的项目库在那里(没有“-l”)。也在较低的 部分,您可以添加自定义路径到搜索库

【讨论】:

  • 非常感谢,如果你每次都在terminal 中编写命令,这对 Eclipse 用户来说很烦人……而且还有更多的缺点。不管怎样,谢谢 !如果可以的话,+10 :)
【解决方案2】:

链接时,您必须在命令行中添加标志-pthread-lrt。它就在manual page 中。

【讨论】:

    【解决方案3】:

    正如您链接的问题的第一个答案中所写,您需要以这种方式编译它:

    gcc source.c -lpthread

    -lrt-pthread 也会这样做。

    【讨论】:

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