Makefile for Shared Libraries?

19,309

Solution 1

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.

Solution 2

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
Share:
19,309

Related videos on Youtube

dwc
Author by

dwc

Updated on June 04, 2022

Comments

  • dwc
    dwc almost 2 years

    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?

  • dwc
    dwc almost 15 years
    I'm fine with per platform flags. I'm really asking about make rules. See edited question, thanks.
  • visual_learner
    visual_learner almost 15 years
    dwc, the job of writing per-platform flags has been done. It's called Autotools. I promise you it will be a thousand times easier than what you seem to want to do (which looks like building your own Autotools from scratch).
  • dwc
    dwc almost 15 years
    libtool seems to be the best way. It's a shame the manual throws you to the wolves (see gnu.org/software/libtool/manual/libtool.html#Makefile-rules) unless you're using the whole Autotools suite.