使用 pthreads 创建 makefile

use*_*932 3 c posix semaphore makefile pthreads

我想创建一个支持 posix 信号量的 makefile。这就是我到目前为止所得到的:

CFLAGS=-g -ansi -pedantic -Wall -Werror -D_XOPEN_SOURCE=600
LDFLAGS=-pthread 
CC=gcc
OBJECTS=MsgQueueMain.o MsgQueue.o Queue.o MyMalloc.o
TARGET=MsgQueueMain

all: $(TARGET)

$(TARGET): $(OBJECTS)
    $(CC) $(OBJECTS) -o $@

include depends

depends:
    $(CC) -MM $(OBJECTS:.o=.c) > depends

clean:
    rm ./$(TARGET) *.o
Run Code Online (Sandbox Code Playgroud)

出于某种原因,我收到了对 semaphore.h api 函数的所有调用的“未定义引用”。

hmj*_*mjd 5

您需要链接rtpthread库。来自man sem_destroy参考页面:

与 -lrt 或 -pthread 链接。

添加到编译器命令的末尾,因为顺序很重要(不确定顺序是否重要,-pthread因为这定义了一些宏并添加-lpthread)。

正如评论说弗拉德拉扎连科LDFLAGS不是你的一部分TARGET。改成:

$(CC) $(OBJECTS) -o $@ $(LDFLAGS)

  • 他的问题是在他的 `$(TARGET)` 构建命令中没有指定 `LDFLAGS`,而不是因为他不知道需要 `-pthread`... (2认同)