Search code examples
linuxmakefilelinkerlibxlsxwriter

Setting path to shared library inside a makefile for compile


I want to compile a program using makefile which is linked against the zlib shared libraries which it is different from the one installed on my system. But I don't want them to be permanently added to the library pool of my system.

The path of custom zlib is /usr/work/libxlsxwriter-master/zlib-1.2.8

I have tried to use something like:

ZLIBDIR=/usr/work/libxlsxwriter-master/zlib-1.2.8

# The static library.
$(LIBXLSXWRITER_A) : $(OBJS)
    export LD_LIBRARY_PATH=$(ZLIBDIR):$(DEPENDENCIES); \
    $(Q)$(AR) $(ARFLAGS)     $@ $(MINIZIP_DIR)/ioapi.o $(MINIZIP_DIR)/zip.o  $^

 # The dynamic library.
 $(LIBXLSXWRITER_SO) : $(SOBJS)
    export LD_LIBRARY_PATH=$(ZLIBDIR):$(DEPENDENCIES); \
    $(Q)$(CC) $(SOFLAGS)  -o $@ $(MINIZIP_DIR)/ioapi.so $(MINIZIP_DIR)/zip.so $^ -lz

# Targets for the object files.
%.o  : %.c $(HDRS)
    $(Q)$(CC)       -I$(INC_DIR) $(CFLAGS) $(CXXFLAGS) -c $<

 %.so : %.c $(HDRS)
    $(Q)$(CC) -fPIC -I$(INC_DIR) $(CFLAGS) $(CXXFLAGS) -c $< -o $@

  %.to : %.c $(HDRS)
    $(Q)$(CC) -g -O0 -DTESTING -I$(INC_DIR) $(CFLAGS) $(CXXFLAGS) -c $< -o $@

When I try to compile, I have this error : /bin/sh: line 1: @ar: command not found

Where I'm wrong ?


Solution

  • Where I'm wrong ?

    You are wrong in that you modified your Makefile incorrectly.

    You have a macro Q, which evaluates to @, which makes the make quiet (not print the command it executes) if @ is the first character of the command line. By prepending LD_LIBRARY_PATH to the command line, you screwed that up:

    # this is a quiet command:
    @ar ...
    
    # this is a not quiet command, which tries to execute @ar, which doesn't exist:
    LD_LIBRARY_PATH=... ; @ar ...
    

    The second part of wrong is that setting LD_LIBRARY_PATH as you did only affects the building of the libraries (i.e. the compiler and the linker). What you want is to affect the runtime using these libraries, not the compiler and linker used to build them.

    As DevSolar correctly stated, you want -rpath instead:

    $(Q)$(CC) $(SOFLAGS) -o $@ $(MINIZIP_DIR)/ioapi.so \
      -Wl,-rpath=$(ZLIBDIR) $(MINIZIP_DIR)/zip.so ...