Reputation: 1869
I'm trying to build multiple shared libraries in one makefile. This is what I'm using to build one shared library:
CC = gcc # C compiler
PWD := $(shell pwd)
CFLAGS = -fPIC -Wall -Wextra -O2 -g # C flags
LDFLAGS = -shared # linking flags
RM = rm -f # rm command
CFLAGS += $(DFLAGS)
TARGET_LIB := lib1.so # target lib
#TARGET_LIB += lib2.so
SRCS := lib1.c # source files
#SRCS += lib2.c # source files
OBJS = $(SRCS:.c=.o)
.PHONY: all
all: $(TARGET_LIB)
$(TARGET_LIB): $(OBJS)
$(CC) $(INC) $(LDFLAGS) $(CFLAGS) -o $@ $^
However, I can't just uncomment the lines for lib2 and have it being built as well. It's likely because $(TARGET_LIB): $(OBJS)
expands to lib1.so lib2.so : lib1.o lib2.o
which isn't what I want.
Instead, I want something like
lib1.so : lib1.o
lib2.so : lib2.o
But I'm not sure how to do so or what it is called. Can someone tell me what to do to achieve what I'm looking for?
EDIT: I should have been more clear. I realize you can add more targets to build these. But is there a way to do it without having to write a new target everytime I want to add a new library?
Thanks.
Upvotes: 0
Views: 4555
Reputation: 6395
The implicit rules are for that. Read about them in the GNU Make manual.
Replace
$(TARGET_LIB): $(OBJS)
with
%.so: %.c
Upvotes: 0
Reputation: 8333
You can do it by separating targets like this:
CC = gcc # C compiler
PWD := $(shell pwd)
CFLAGS = -fPIC -Wall -Wextra -O2 -g # C flags
LDFLAGS = -shared # linking flags
RM = rm -f # rm command
CFLAGS += $(DFLAGS)
TARGET_LIB1 = lib1.so # target lib
TARGET_LIB2 = lib2.so
TARGET_LIBS = $(TARGET_LIB1) $(TARGET_LIB2)
SRCS1 = lib1.c # source files
SRCS2 = lib2.c # source files
SRCS = $(SRCS1) $(SRCS2)
OBJS1 = $(SRCS1:.c=.o)
OBJS2 = $(SRCS2:.c=.o)
OBJS = $(OBJS1) $(OBJS2)
.PHONY: all
all: $(TARGET_LIBS)
$(TARGET_LIB1): $(OBJS1)
$(CC) $(INC) $(LDFLAGS) $(CFLAGS) -o $@ $^
$(TARGET_LIB2): $(OBJS2)
$(CC) $(INC) $(LDFLAGS) $(CFLAGS) -o $@ $^
Upvotes: 0
Reputation: 725
You can separate sources of two libraries into different directories. It also may help in further maintenance of your libraries. Then use one make file which will trigger corresponding sub-makefiles. I may be better than one big makefile
Upvotes: 0
Reputation: 338
You can do something like this -
all : lib1.so lib2.so
and provide rules to make lib1.so and lib2.so
Upvotes: 2