【问题标题】:Can't compile code with semaphore under Solaris?Solaris下不能用信号量编译代码?
【发布时间】:2011-11-07 11:06:14
【问题描述】:

我编写了一些在 linux 下编译良好的代码,但在 Solaris 上我得到了一些编译错误。我使用gcc test_compile.c -o tes -pthreads编译。

#include <semaphore.h>

int main(){
    sem_t semaphore;
    sem_init(&semaphore, 0, 0);
    return 0;
}

给我

itchy:~/edu/sysprog> gcc test_compile.c -o tes -pthreads
Undefined                       first referenced
 symbol                             in file
sem_init                            /var/tmp//ccUiSK6A.o
ld: fatal: Symbol referencing errors. No output written to tes

我不确定发生了什么。我尝试用sema_init 替换sem_init 并编译(在网上某处看到)。但是,这意味着我必须检查整个代码并将 sem 替换为 sema。没有更简单的解决方案吗?它的真正含义是什么?

【问题讨论】:

  • 您收到构建时错误,但这不是编译器错误。不幸的是,“编译”一词已被用来表示“构建可执行文件”,但两者并不相同。您的问题出在链接器上。

标签: c solaris linker-errors semaphore build-error


【解决方案1】:

你需要链接实时扩展库librt

gcc test_compile.c -o tes -lrt -pthreads

这在sem_init(3RT) 的手册页中有记录:

SYNOPSIS
     cc [ flag... ] file... -lrt [ library... ]
     #include <semaphore.h>

     int sem_init(sem_t *sem, int pshared, unsigned int value);

【讨论】:

  • 我不确定这是不是真的。 This manpage 似乎表明您需要与pthreadslrt 链接。与 pthread 链接最有意义 (imo)。
  • 您链接到 Linux 手册页。我引用了上面的 Solaris 手册页,并在 Solaris 10 上对其进行了测试。从某种意义上说,您是对的它不应该造成任何伤害(二进制大 24 字节!)。
  • 那么是-pthreads 还是-lpthreads?抱歉,我还没有测试环境。
  • -pthreads 用于旧版本的 gcc-lpthreads 用于较新版本
【解决方案2】:

在所有这些之前,我首先要确保您的链接正确。似乎编译得很好,但在链接步骤中失败了。所以首先确保你确实拥有semaphore.h,并且它包括sem_init(...)。如果你这样做了,我猜你是这样做的,请检查你的编译命令。如果这是您问题中的编译命令,请尝试将 -lpthread 添加到您的编译行以链接到 posix 线程库。


因此,您应该仔细检查 sema 是否符合您的要求,因为它们是不同的库——sem 来自 POSIX pthreads 库,sema 来自 solaris thread 库。 (See this also) 但是,如果它们是代码兼容的,并且如果您正在寻找跨平台兼容的代码,您可能想要做一些事情,比如创建简单的包装函数,然后有条件地包含它。

您的包装函数将非常简单,接受相同的类型并返回相同的类型,例如

ret_type sem_init(argtype arg1, argtype arg2, argtype arg3)
{
    return sema_init(arg1, arg2, arg3)
}

然后有条件地用类似的东西包含它

#ifdef SOLARIS
#include semaphore_wrappers.h
#endif

请注意,不会定义 SOLARIS。在 solaris 上编译时,您要么必须手动 #define SOLARIS,要么在编译命令行/makefile 中定义它。

至少我会这样做。

请注意,如果这不是跨平台兼容的,那么如果您只进行全局搜索和替换,则阅读和调试会容易得多。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-07-26
  • 2014-06-26
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-19
  • 2017-11-09
相关资源
最近更新 更多