c语言 - 无法在 Solaris 下使用信号量编译代码?



我写了一些代码,在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,它编译(在网上某处看到)。然而,这意味着我必须遍历整个代码并用sema替换sem。难道没有更简单的解决办法吗?它到底是什么意思呢?

您需要链接到实时扩展库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);

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


所以你应该仔细检查sema是否做了你想要的,因为它们是不同的库——sem来自POSIX pthreads库,sema来自solaris thread库。但如果它们是代码兼容的,如果你正在寻找跨平台兼容的代码,你可能会想做一些事情,比如创建简单的包装器函数,然后有条件地包含它。

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

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中定义它。

至少我是这么做的。

请注意,如果不是是跨平台兼容的,那么如果您只是执行全局搜索并替换

,则更容易阅读和调试。

最新更新