Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Makefile for Shared Libraries?

I've just written a Makefile to build a shared library, similar to the following:

libmystuff.so: CFLAGS+=-fPIC -shared
libmystuff.so: libmystuff.o otherstuff.o
    $(CC) $(CFLAGS) -o $@ $^

I like to avoid doing explicit actions when this seems like a common operation, but it seems there's no implicit rule or other built-ins to standardize this. I'm using GNU Make on Linux at the moment, but will need this to work on OS X as well.

EDIT: I'm asking about make rules rather than compiler/linker flags.

Can you recommend clean, reusable Makefile rules to build shared libs? Perhaps a %.so: or .c.so: type rule?

like image 218
dwc Avatar asked May 19 '09 23:05

dwc


2 Answers

For portability, I'd look into integrating libtool.

define compile_rule
        libtool --mode=compile \
        $(CC) $(CFLAGS) $(CPPFLAGS) -c $<
endef
define link_rule
        libtool --mode=link \
        $(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS)
endef

LIBS = libmystuff.la
libmystuff_OBJS = libmystuff.lo otherstuff.lo

%.lo: %.c
        $(call compile_rule)

libmystuff.la: $(libmystuff_OBJS)
        $(call link_rule)

install/%.la: %.la
        libtool --mode=install \
        install -c $(notdir $@) $(libdir)/$(notdir $@)
install: $(addprefix install/,$(LIBS))
        libtool --mode=finish $(libdir)

libtool will automatically add -fPIC/-DPIC/-shared flags as appropriate, and generate whatever .o/.a/.so files would be used on the current platform.

Or you could use Automake's libtool integration.

like image 166
ephemient Avatar answered Oct 06 '22 01:10

ephemient


Building shared libraries is platform dependent. For example, the flags you are using are ok for GCC for ELF platforms, for cygwin, for example, you do not add -fPIC for some other platforms and compilers you need other flags.

You need one of:

  • Provide an option to set flags for user platform.
  • Use standard build system like Autotools
like image 28
Artyom Avatar answered Oct 05 '22 23:10

Artyom