Dulguuntur
Dulguuntur

Reputation: 51

How to create static and dynamic library in Makefile?

How to create dynamic and static library in Makefile. I have C codes. In inc folder there is all of header files included and outside of this folder C files included. I want to create .a and .so library.How do i include wildcard which illustrates all the files will be executed. I tried this way.

CFLAGS := -fPIC -O3 -g -Wall -Werror
CC := gcc
MAJOR := 0
MINOR := 1
NAME := foo
VERSION := $(MAJOR).$(MINOR)

lib: lib$(NAME).so

lib$(NAME).so.$(VERSION): $(NAME).o
    $(CC) -shared -Wl,-soname,lib$(NAME).so.$(MAJOR) $^ -o $(wildcard %.c)

clean:
    $(RM) *.o *.so*

Upvotes: 1

Views: 5511

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754820

CFLAGS := -fPIC -O3 -g -Wall -Werror
CC := gcc
MAJOR := 0
MINOR := 1
NAME := foo
VERSION := $(MAJOR).$(MINOR)

LIBSO  = lib$(NAME).so
LIBSOM = $(LIBSO).$(MAJOR)
LIBSOV = $(LIBSO).$(VERSION)
LIBA   = lib$(NAME).a

lib: $(LIBSO) $(LIBA)

$(LIBSO): $(LIBSOV)
     ln -s $(LIBSOV) $(LIBSO)

$(LIBSOV): $(NAME).o
    $(CC) $(CFLAGS) -shared -Wl,-soname,$(LIBSOM) -o $(LIBSOV) $(NAME).o

$(LIBA): $(NAME).o
    $(AR) $(ARFLAGS) $(LIBA) $(NAME).o

clean:
    $(RM) *.o *.so*

Check to make sure that macros AR and ARFLAGS are set appropriately (ar and ru or thereabouts — I usually use ruv).

I'm not clear why you have a single object file foo.o, or whether in fact you wanted every C source file in the directory compiled into an object file and included in the library — your linking command for the shared object was not well-formed (it would have overwritten the first .c file as the shared object it created).

If you want more object files in the libraries, then define:

SOURCE := $(wildcard *.c)
OBJECT := $(SOURCE:.c=.o)

and use $(OBJECT) in place of $(NAME).o in the rules. Personally, I don't trust wildcards — there's too much danger of test program code etc being included in the library for my comfort. YMMV.

Upvotes: 3

Related Questions