0

I'm pretty new to Makefiles in C. I am trying to figure out where I would put -lpthread in my makefile so I can implement posix threads in my C program. Below is my Makefile, thanks in advance.

CFLAGS  = -g -Wall
LDFLAGS =
CC      = gcc
LD      = gcc

TARG1   = calc
OBJS1   = calc.o


$(TARG1): $(OBJS1)
    $(LD) $(LDFLAGS) $(OBJS1) -o $(TARG1)
clean:
    rm -rf $(TARG1) $(OBJS1)
johns4ta
  • 886
  • 2
  • 12
  • 38
  • 1
    Typically on the ld line, at the end. – Anya Shenanigans Nov 20 '13 at 23:38
  • So the ld line would be $(LD) $(LDFLAGS) $(OBJS1) -o $(TARG1) -lpthread ? – johns4ta Nov 20 '13 at 23:39
  • 1
    Zan's answer is a better solution, and covers the general case of needing to specify the flag during compiling and linking. In general, you should use variables where possible in makefiles to prevent repetition and potential error. – Anya Shenanigans Nov 20 '13 at 23:45
  • 1
    @user1153018 In case of static libs, the linker only pulls those object files out of the lib that define currently unresolved symbols. That's why you have to put the libraries after the objects, before them there aren't any unresolved symbols (beside main(), possibly) therefore nothing would get linked. – Andreas Bombe Nov 21 '13 at 00:04

1 Answers1

3

I would recommend not using -l. Instead give GCC -pthread on both the CFLAGS and LDFLAGS variables. This will make sure that preprocessor defines are properly set during the compile and it will link the correct libraries.

This assumes GCC of course. If using Intel icc or LLVM check for the right parameters.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131