4

I want to create a makefile that supports posix semaphores. That is what I've got so far:

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

For some reason, I'm getting "undefined reference" for all calls to semaphore.h api functions.

user2130932
  • 73
  • 1
  • 1
  • 4
  • 1
    This is probably not related to your prolem, but you need `-pthread` when compiling and linking, so you should add it to `CFLAGS` as well. – Idelic Mar 12 '13 at 20:39

1 Answers1

6

You need to link with the rt or pthread library. From man sem_destroy reference page:

Link with -lrt or -pthread.

Add to the end of the compiler command as order is important (unsure if order is important for -pthread as this defines some macros and adds -lpthread).

As commented by Vlad Lazarenko the LDFLAGS is not part of your TARGET. Change to:

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

Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • 2
    His problem is that `LDFLAGS` is not specified in his `$(TARGET)` building command and not because he doesn't know that `-pthread` is need... –  Mar 12 '13 at 17:13
  • @VladLazarenko, well spotted. I completely missed that. – hmjd Mar 12 '13 at 17:14