【问题标题】:undefined reference to `pthread_create' -pthread not working未定义对“pthread_create”的引用 -pthread 不起作用
【发布时间】:2018-03-25 17:41:24
【问题描述】:

我正在一个函数中创建新线程,并且我已经包含了 pthread.h。但它不起作用,我在编译时不断收到以下错误:

对 `pthread_create' 的未定义引用

我用来编译的标志如下:

CFLAGS=-std=gnu99 -pthread -g -Wall -Wextra -Werror -Wmissing-declarations -Wmissing-prototypes -Werror-implicit-function-declaration -Wreturn-type -Wparentheses -Wunused -Wold-style-definition -Wundef -Wshadow -Wstrict-prototypes -Wswitch-default -Wunreachable-code

编译器是gcc

生成文件:

CC=gcc
CFLAGS=-std=gnu99 -pthread -g -Wall -Wextra -Werror -Wmissing-declarations -Wmissing-prototypes -Werror-implicit-function-declaration -Wreturn-type -Wparentheses -Wunused -Wold-style-definition -Wundef -Wshadow -Wstrict-prototypes -Wswitch-default -Wunreachable-code

all: finder

finder: stack.o list.o finder.o
    $(CC) -o mfind stack.o list.o mfind.o

stack.o: stack.c stack.h
    $(CC) -c stack.c $(CFLAGS)

list.o: list.c list.h
    $(CC) -c list.c $(CFLAGS)

finder.o: finder.c finder.h
    $(CC) -c finder.c $(CFLAGS)

clean:
    rm -f *.o finder

【问题讨论】:

  • CFLAGS 通常是放置链接库的错误变量,许多构建系统将CFLAGS 放在命令行要链接的文件之前。您的构建系统可能会提供一个LIBS 变量,您可以在其中放置-pthread。没有足够的信息可以确定。
  • 当您遇到此错误时,您正在运行什么 exact 命令?
  • 可用的最少代码?
  • @Cows42 然后显示 Makefile 的(相关部分)。我敢打赌有类似gcc -o$@ $(CFLAGS) $< 的链接。 -pthread 必须出现在输入文件之后。
  • $(CC) -o mfind stack.o list.o mfind.o 中的哪个位置是-pthread 或包含-pthread 的变量?

标签: c pthreads


【解决方案1】:

-pthread 在链接阶段需要,而不是在编译单个翻译单元时。典型的方法如下所示:

CC=gcc
CFLAGS=-std=gnu99 -g -Wall -Wextra -Werror -Wmissing-declarations -Wmissing-prototypes -Werror-implicit-function-declaration -Wreturn-type -Wparentheses -Wunused -Wold-style-definition -Wundef -Wshadow -Wstrict-prototypes -Wswitch-default -Wunreachable-code
LIBS=-pthread

all: finder

finder: stack.o list.o finder.o
    $(CC) -o mfind stack.o list.o mfind.o $(LIBS)

stack.o: stack.c stack.h
    $(CC) -c stack.c $(CFLAGS)

list.o: list.c list.h
    $(CC) -c list.c $(CFLAGS)

finder.o: finder.c finder.h
    $(CC) -c finder.c $(CFLAGS)

clean:
    rm -f *.o finder

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2013-06-20
    • 1970-01-01
    相关资源
    最近更新 更多