2

I have a C program that I have been working on across multiple machines, and although it compiles correctly on my MacBook, I cannot get the program to compile on the Windows Subsystem for Linux, running Ubuntu 18.04 and using gcc.

The program spawns multiple threads, and when I try to compile it on the Windows Subsystem I get the error undefined reference to `pthread_create.

Several other questions, such as this, this, and this, suggest using -lpthread as a compiler flag to solve the issue, but I am already doing this and it compiles fine on OSX, so I suspect the issue might be related to my WSL configuration.

My Makefile is:

CC = gcc
CCOPTS = -Wall -c -g -ggdb
LINKOPTS = -Wall -g -ggdb -lpthread

all: calc

calc: calc.o smp3_tests.o testrunner.o
    $(CC) $(LINKOPTS) -o $@ $^

calc.o: calc.c calc.h
    $(CC) $(CCOPTS) -o $@ $<

I am including the pthread header with #include <pthread.h> and calling the pthread_create function with pthread_create(&multiplierThread, NULL, multiplier, arg).

Does anyone know what could be causing this compiler error?

Jared Forth
  • 1,577
  • 6
  • 17
  • 32
  • 1
    I don’t know anything about WSL but unless it’s using a different convention from the GNU toolchain, don’t use `CCOPTS` and `LINKOPTS`, use the conventional variable names (i.e. `CFLAGS` and `LDFLAGS`). If for no other reason then because it makes explicitly writing the other rules redundant. – Konrad Rudolph Apr 09 '19 at 14:21
  • 1
    Closely related: [Difference between -pthread and -lpthread while compiling](https://stackoverflow.com/q/23250863/2402272). – John Bollinger Apr 09 '19 at 14:21

1 Answers1

6

Overall, with GCC you ought to be using the -pthread option for both compiling your sources and linking your objects. You do not then need (nor really want) to include -lpthead explicitly among your link libraries:

CC = gcc
CFLAGS = -Wall -c -g -ggdb -pthread
LDFLAGS= -Wall -g -ggdb -pthread

calc: calc.o smp3_tests.o testrunner.o
    $(CC) $(LDFLAGS) -o $@ $^

calc.o: calc.c calc.h
    $(CC) $(CFLAGS) -o $@ $<

If you do link -lpthread explicitly, however, then the order in which object files and -l options appear in the link command is significant to many linkers. If given at all, then the -lpthread option should appear at the end of the link command, after all object files that call functions it is expected to provide.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157