首页 > 解决方案 > 链接器找不到信号量函数

问题描述

我正在尝试制作一个 C 程序,它将执行子进程,这些子进程将使用信号量进行交互。然后我编译代码,gcc 抛出引用错误——因为它不知道函数“sem_init”、“sem_post”和“sem_wait”,即使我包含 semaphore.h 库。

这是它的外观:

代码:

#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>

#define LETTER_COUNT 26
#define THREADS 2

char letter[LETTER_COUNT] = "aBCDefghiJklMNoPqrsTuvWxyZ";

pthread_t t[THREADS];
sem_t sem[THREADS];

void print_letter(void) {
    //print string
}

void* reorder(void* d) {
    (void)d;
    //do some work
    return NULL;
}

void* switch_case(void* d) {
    (void)d;
    //do some work
    return NULL;
}

int main(void) {
    int i;
    for(i = 0; i < THREADS; i++) {
        if(sem_init(&sem[i], 0, 0) == -1) {
            perror("sem_init");
            return -1;
        }
    }
    pthread_create(&t[0], NULL, reorder, NULL);
    pthread_create(&t[1], NULL, switch_case, NULL);
    while(1) {
        i = (i + 1) % (THREADS - 1);
        sem_post(&sem[i]);
        sem_wait(&sem[2]);
        print_letter();
        sleep(1);
    }
    return 0;
}

错误:

gcc -Wall task4.c -o task4.o
Undefined                       first referenced
 symbol                             in file
sem_init                            /var/tmp//cc0i56ka.o
sem_post                            /var/tmp//cc0i56ka.o
sem_wait                            /var/tmp//cc0i56ka.o
ld: fatal: symbol referencing errors. No output written to task4.o
collect2: ld returned 1 exit status

我正在尝试查找有关此问题的一些信息,但找不到任何可行的解决方案。也许我应该使用一些编译标志(如-lsocket)?

标签: ccompilationsemaphore

解决方案


根据 man sem_init (和朋友)

gcc -Wall task4.c -o task4.o -lpthread

在某些系统上,“librt”共享库是针对共享 libpthread 构建的,引用 -lrt 将暗示 -lpthread。但是,手册页指示要使用的正确链接命令-pthread,请参见下文。请注意-pthread,根据需要,通常会调用 MT 语义,-lpthread但也会调用其他库、标志或 #defines。例如,在 GCC/Mint19 上,它将定义-D_REENTRANT.

man sem_init

AME sem_init - 初始化一个未命名的信号量

概要#包括

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

   Link with -lpthread.

man gcc

Options Controlling the Preprocessor

   -pthread
       Define additional macros required for using the POSIX threads library.  You should use this option consistently for both compilation
       and linking.  This option is supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets.

Options for Linking

  -pthread
       Link with the POSIX threads library.  This option is supported on GNU/Linux targets, most other Unix derivatives, and also on x86
       Cygwin and MinGW targets.  On some targets this option also sets flags for the preprocessor, so it should be used consistently for both
       compilation and linking.

推荐阅读