我正在尝试制作一个C程序,该程序将执行子进程,这些子进程将使用信号量进行交互。 然后我编译代码,gcc抛出引用错误-因为即使我包括semaphore.h库,它也不知道函数“ sem_init”,“ sem_post”和“ sem_wait”。
外观如下:
代码:
#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)?
答案 0 :(得分:1)
根据人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-初始化未命名的信号量
简介 #include
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.