问题
I have built a shared library (i.e libabc.so) and an executable (i.e myapp) which uses my shared library. I have placed both the shared library and my executable in my filesystem but when I run my executable it gives me the following error
error while loading shared libraries: <target_lib_path>/<mylib>.so cannot open shared object file: No such file or directory.
Now my dev environment is I have a different target filesystem which is placed at ~/targetfs after building my shared library I am installing it in ~/targetfs/usr/local/abc/lib. During linking my application I give it
LDFLAGS += -L~/targetfs/usr/local/abc/lib
My application builds fine. But when I run my application in an environment where ~/targetfs is my filesystem, then my application complains
error while loading shared libraries:
/home/user/targetfs/usr/local/abc/lib/libabc.so: can not open shared object file. No such file or directory exist.
Now, of course the path my application is searching for the shared library that does not exist, but I want my application to be independent of this path, rather it should look for my shared library in /lib, /usr/lib, /usr/local/lib or LD_LIBRARY_PATH location.
How can I make my application to link libraries independent of its location?
Makefiles for my shared library & application is given below.
-------------- Shared library makefile. (Omitting un-necessary info)
CC = $(CROSS_COMPILE)gcc
CFLAGS = -Wall -shared -fpic
LDFLAGS = -Xlinker --gc-sections --allow-shlib-undefined
LIBRARY = libabc.so
OBJ_DIR = obj
SRC_DIR = src
CHK_DIR_EXISTS = test -d
MKDIR = mkdir -p
# Project Source Files
C_SOURCES += $(SRC_DIR)/abc.c
OBJECTS += $(OBJ_DIR)/abc.o
INCLUDES += -Iinc
$(LIBRARY): $(OBJECTS)
@echo ""
@echo "Linking..." $(LIBRARY)
@$(CC) $(CFLAGS) $(LDFLAGS) $(OBJECTS) -o $(OBJ_DIR)/$(LIBRARY)
---------- Application Makefile (Omitting un-necessary info)
LDFLAGS += $(TARGETFS)/usr/local/abc/lib/libabc.so \
-lpthread -lrt
Any thoughts what's missing in my Makefiles.
回答1:
You can ask the linker to put multiple search paths into the binary. You introduce those search paths with the -Wl,rpath=... option.
gcc -o abc abc.c
-L~/targetfs/usr/local/abc/lib
-labc
-Wl,-rpath=/usr/local/abc/lib
-Wl,-rpath=...
-Wl,-rpath=...
来源:https://stackoverflow.com/questions/9482984/how-can-i-make-my-application-to-link-libraries-independent-of-its-location