2
votes

I'm creating new threads in a function, and I've included pthread.h. But it's not working, I keep receiving the following error upon compiling:

undefined reference to `pthread_create'

The flags I'm using to compile are the following:

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

The compiler is gcc

Makefile:

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
1
CFLAGS is normally the wrong variable to put linked libraries into, many build systems put the CFLAGS on the command line before the files to be linked. Your build system might offer a LIBS variable where you can put -pthread. Not enough information to tell for sure.user2371524
And what exact command are you running when you get this error?Chris Turner
minimal code available?CS Pei
@Cows42 then show the (relevant parts of the) Makefile. I bet there's something like gcc -o$@ $(CFLAGS) $< for linking. -pthread must appear after the input files.user2371524
Where in $(CC) -o mfind stack.o list.o mfind.o is -pthread or a variable that contains -pthread?Chris Turner

1 Answers

5
votes

-pthread is needed at the linking stage, not when compiling the individual translation units. A typical approach would look like this:

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