problems with Makefile
everyone, I have this snippet of the code, and also I have an error:
CC = gcc
SRCS_L = a.c b.c c.c d.c
OBJS_L = a.o b.o c.o d.o
SRCS_R = x.c y.c
OBJS_R = x.o y.o
LIBRARY = lib.a
PROG = prog
FLAGS = -c -D_GNU_SOURCE
CLEAN = clean
all: $(LIBRARY) $(PROG) $(CLEAN)
$(LIBRARY): $(OBJS_L)
$(CC) $(FLAGS) $(SRCS_L) -lpthread
ar -r lib.a $(OBJS_L)
$(PROG): $(OBJS_R)
$(CC) $(FLAGS) $(SRCS_R) -lpthread lib.a
$(OBJS_R) -o $(PROG)
$(CLEAN):
开发者_运维知识库 rm -rf *.o
can somebody tell me what am I doing here wrong? I receive an error which tells me that it is impossible to make second target (PROG) and also can't make c.o, why? thanks in advance
edited
-lpthread - I'm trying to link library
I've upvoted Banthar's answer, but on a side note I thought I'd mention that using substitution for your object files will make your Makefile less error-prone.
For example:
SRCS_L = a.c b.c c.c
OBJS_L = $(SRCS_L:.c=.o)
OBJS_L will always be a list of object files for the sources defined in SRCS_L.
For the -lpthread problem:
Only link to libraries when creating your executable.
Original:
$(CC) $(FLAGS) $(SRCS_R) -lpthread lib.a
$(OBJS_R) -o $(PROG)
Fixed:
$(CC) $(FLAGS) $(SRCS_R) lib.a
$(CC) -lpthread $(LIBRARY) $(OBJS_R) -o $(PROG)
Also, I highly recommend separating your executable and library into separate Makefiles. Doing so will allow you to move and reuse your library more easily and simplify the logic of your Makefiles.
For instance:
LIBRARY=my_lib.a
CC=gcc
SOURCES=$(wildcard *.c)
OBJECTS=$(SOURCES:.c=.o)
CFLAGS=-c -g -Wall
build: $(OBJECTS)
ar rcs $(LIBRARY) $(OBJECTS)
clean:
rm -rf $(LIBRARY) $(OBJECTS)
rebuild: clean build
$(OBJECTS):
$(CC) $(CFLAGS) $(@:.o=.c) -o $@
Using a Makefile for you library as the one above means that you do not have to edit the Makefile whenever you add or remove a source file. Make note, however, that you will need to dedicate a separate directory for your library for Makefiles such as this to work properly.
$(OBJS_R) -o $(PROG)
Should be:
$(CC) $(OBJS_R) -o $(PROG)
精彩评论