gcc中的-Wl,rpath=<your_lib_dir>选项

本文介绍使用GCC编译器进行动态库链接时遇到的问题及解决方案,详细解释了-L选项的作用以及如何通过-Wl,-rpath选项确保运行时正确找到动态链接库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

gcc编译链接动态库时,很有可能编译通过,但是执行时,找不到动态链接库,那是

因为-L选项指定的路径只在编译时有效,编译出来的可执行文件不知道-L选项后面的值,

当然找不到。可以用ldd <your_execute>看看是不有 ‘not found’在你链接的库后面,

解决方法是通过-Wl,rpath=<your_lib_dir>,使得execute记住链接库的位置

gcc -o foo foo.c -L/usr/local/lib -lfoo -Wl,-rpath=/usr/local/lib
gcc -o foo foo.c -L$(prefix)/lib -lfoo -Wl,-rpath=$(prefix)/lib
 

Re: linking with -Wl,-rpath and $(prefix)

  • From: "Nelson H. F. Beebe" <beebe at math dot utah dot edu>
  • To: gcc-help at gcc dot gnu dot org
  • Cc: beebe at math dot utah dot edu, "David Carter-Hitchin" <david at carter-hitchin dot clara dot co dot uk>
  • Date: Fri, 2 Dec 2005 17:18:18 -0700 (MST)
  • Subject: Re: linking with -Wl,-rpath and $(prefix)

"David Carter-Hitchin" <david@carter-hitchin.clara.co.uk> asks on
Fri, 2 Dec 2005 23:47:28 -0000 about -Wl,-rpath versus -L.

The -L option supplies a colon-separated library path that is to be
searched at LINK TIME for libraries. Thus

	cc -o foo foo.c -L/usr/local/lib -lfoo

means that either libfoo.a or libfoo.so should be found in either
/usr/local/lib, or elsewhere in the default search patch (in
GNU/Linux, the directories can be listed in /etc/ld.so.conf, and the
cache updated by running /etc/ldconfig).

Whether the .a or .so form of the library is needed is platform
dependent (e.g., IBM AIX uses only the .a form), and also dependent on
compiler options to select dynamic or static linking.  The default is
normally dynamic linking to save disk space and waste CPU time.

However, this means while that the executable foo may have been
successfully linked against a shared library, at RUN TIME, the
run-time loader looks for it in the default search path, possibly
prefixed by a colon-separated list of libraries supplied by the
LD_LIBRARY_PATH variable.

If, in our example, /usr/local/lib is not part of the default path,
then the run-time loader will not be able to find the shared library,
EVEN THOUGH LINKING SUCCEEDED (because of the -L/usr/local/lib
option).

You can check whether shared libraries can be found by running

	env -i ldd foo

(the "env -i" says to ignore any existing environment variables, such
as LD_LIBRARY_PATH).

For example, on one of my systems, I find

	% env -i ldd /usr/local/bin/emacs
		libXaw3d.so.5 =>         (file not found)
		libXmu.so.4 =>   /usr/lib/libXmu.so.4
		libXt.so.4 =>    /usr/lib/libXt.so.4
		...

Notice the "(file not found") line.  That library is actually present
on that system in /usr/local/lib, and I can make it succeed like this:

	% env -i LD_LIBRARY_PATH=/usr/local/lib ldd /usr/local/bin/emacs
	        libXaw3d.so.5 =>         /usr/local/lib/libXaw3d.so.5
        	libXmu.so.4 =>   /usr/lib/libXmu.so.4
		...

Thus, when shared libraries are present in nondefault directories, you
need to supply an additional linker option, usually -R or -Wl,-rpath=,
with a run-time library path.  Our example above becomes for gcc

	gcc -o foo foo.c -L/usr/local/lib -lfoo -Wl,-rpath=/usr/local/lib

In a Makefile, I would write this as

	gcc -o foo foo.c -L$(prefix)/lib -lfoo -Wl,-rpath=$(prefix)/lib

so that the same library path is used at link time as at run time, and
so that the executable file, foo, records that path.  With GNU
autoconf, the normal condition is that prefix is the root of the file
tree into which you install software locally, so the above command is
fairly typical.  Unfortunately, software developers who have
nondefault library search paths often forget to supply the -Wl,-rpath
or -R options in their Makefiles, with the result that the code builds
and runs at their sites, but not at end user sites.

>From notes that I keep:

>> ...
>> Unfortunately, there are at least three incompatible kinds of
>> command-line options that tell the compiler to instruct the linker to
>> save library paths in the executable:
>>
>> 	-Wl,-rpath,/path/to/dir		gcc, g++, FreeBSD, SGI, Sun compilers
>> 	-rpath /path/to/dir		Compaq/DEC, SGI compilers
>> 	-Rdir:dir:dir			Portland Group, Sun compilers
>>
>> Notice that SGI and Sun support two such flavors.
>> ...

In my view, there is clearly brain damage here: (1) compiler writers
should have standardized on the same option name for recording the
run-time library path (I'd vote for -R), and (2) the linker should
really record the run-time library path by default, so that -R would
almost never be needed.

-------------------------------------------------------------------------------
- Nelson H. F. Beebe                    Tel: +1 801 581 5254                  -
- University of Utah                    FAX: +1 801 581 4148                  -
- Department of Mathematics, 110 LCB    Internet e-mail: beebe@math.utah.edu  -
- 155 S 1400 E RM 233                       beebe@acm.org  beebe@computer.org -
- Salt Lake City, UT 84112-0090, USA    URL: http://www.math.utah.edu/~beebe  -
-------------------------------------------------------------------------------

CMake Error at /home/sniper/anaconda3/envs/yolov8/lib/python3.8/site-packages/cmake/data/share/cmake-3.25/Modules/CMakeTestCCompiler.cmake:70 (message): The C compiler "/usr/bin/gcc" is not able to compile a simple test program. It fails with the following output: Change Dir: /opt/projects/tensorrt-alpha/yolov8/build/CMakeFiles/CMakeScratch/TryCompile-TrXrKM Run Build Command(s):/usr/bin/make -f Makefile cmTC_7d457/fast && /usr/bin/make -f CMakeFiles/cmTC_7d457.dir/build.make CMakeFiles/cmTC_7d457.dir/build make[1]: 进入目录“/opt/projects/tensorrt-alpha/yolov8/build/CMakeFiles/CMakeScratch/TryCompile-TrXrKM” Building C object CMakeFiles/cmTC_7d457.dir/testCCompiler.c.o /usr/bin/gcc --sysroot=/usr/ -march=x86-64 -o CMakeFiles/cmTC_7d457.dir/testCCompiler.c.o -c /opt/projects/tensorrt-alpha/yolov8/build/CMakeFiles/CMakeScratch/TryCompile-TrXrKM/testCCompiler.c Linking C executable cmTC_7d457 /home/sniper/anaconda3/envs/yolov8/lib/python3.8/site-packages/cmake/data/bin/cmake -E cmake_link_script CMakeFiles/cmTC_7d457.dir/link.txt --verbose=1 /usr/bin/gcc --sysroot=/usr/ -march=x86-64 -Wl,-O2 -Wl,--sort-common -Wl,--as-needed -Wl,-z,relro -Wl,-z,now -Wl,--disable-new-dtags -Wl,--gc-sections -Wl,-rpath,/home/sniper/anaconda3/lib -Wl,-rpath-link,/home/sniper/anaconda3/lib -L/home/sniper/anaconda3/lib CMakeFiles/cmTC_7d457.dir/testCCompiler.c.o -o cmTC_7d457 /usr/bin/ld: 找不到 /lib/x86_64-linux-gnu/libc.so.6 于 /usr/ 内部 /usr/bin/ld: 找不到 /usr/lib/x86_64-linux-gnu/libc_nonshared.a 于 /usr/ 内部 /usr/bin/ld: 找不到 /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 于 /usr/ 内部 collect2: error: ld returned 1 exit status make[1]: *** [CMakeFiles/cmTC_7d457.dir/build.make:99:cmTC_7d457] 错误 1 make[1]: 离开目录“/opt/projects/tensorrt-alpha/yolov8/build/CMakeFiles/CMakeScratch/TryCompile-TrXrKM” make: *** [Makefile:127:cmTC_7d457/fast] 错误 2 CMake will not be able to correctly generate this project. Call Stack (most recent call first): CMakeLists.txt:25 (PROJECT) -- Configuring incomplete, errors occurred!
06-02
``` cc := g++ name := pro workdir := workspace srcdir := src objdir := objs stdcpp := c++11 cuda_home := /datav/software/anaconda3/lib/python3.9/site-packages/trtpy/trt8cuda112cudnn8 syslib := /datav/software/anaconda3/lib/python3.9/site-packages/trtpy/lib cpp_pkg := /datav/software/anaconda3/lib/python3.9/site-packages/trtpy/cpp-packages cuda_arch := nvcc := $(cuda_home)/bin/nvcc -ccbin=$(cc) # 定义cpp的路径查找和依赖项mk文件 cpp_srcs := $(shell find $(srcdir) -name "*.cpp") cpp_objs := $(cpp_srcs:.cpp=.cpp.o) cpp_objs := $(cpp_objs:$(srcdir)/%=$(objdir)/%) cpp_mk := $(cpp_objs:.cpp.o=.cpp.mk) # 定义cu文件的路径查找和依赖项mk文件 cu_srcs := $(shell find $(srcdir) -name "*.cu") cu_objs := $(cu_srcs:.cu=.cu.o) cu_objs := $(cu_objs:$(srcdir)/%=$(objdir)/%) cu_mk := $(cu_objs:.cu.o=.cu.mk) # 定义opencv和cuda需要用到的库文件 link_cuda := cudart cudnn link_trtpro := link_tensorRT := nvinfer nvinfer_plugin link_opencv := link_sys := stdc++ dl protobuf link_librarys := $(link_cuda) $(link_tensorRT) $(link_sys) $(link_opencv) # 定义头文件路径,请注意斜杠后边不能有空格 # 只需要写路径,不需要写-I include_paths := src \ $(cuda_home)/include/cuda \ $(cuda_home)/include/tensorRT \ $(cpp_pkg)/opencv4.2/include \ $(cuda_home)/include/protobuf # 定义库文件路径,只需要写路径,不需要写-L library_paths := $(cuda_home)/lib64 $(syslib) $(cpp_pkg)/opencv4.2/lib # 把library path给拼接为一个字符串,例如a b c => a:b:c # 然后使得LD_LIBRARY_PATH=a:b:c empty := library_path_export := $(subst $(empty) $(empty),:,$(library_paths)) # 把库路径和头文件路径拼接起来成一个,批量自动加-I、-L、-l run_paths := $(foreach item,$(library_paths),-Wl,-rpath=$(item)) include_paths := $(foreach item,$(include_paths),-I$(item)) library_paths := $(foreach item,$(library_paths),-L$(item)) link_librarys := $(foreach item,$(link_librarys),-l$(item)) # 如果是其他显卡,请修改-gencode=arch=compute_75,code=sm_75为对应显卡的能力 # 显卡对应的号码参考这里:https://developer.nvidia.com/zh-cn/cuda-gpus#compute # 如果是 jetson nano,提示找不到-m64指令,请删掉 -m64选项。不影响结果 cpp_compile_flags := -std=$(stdcpp) -w -g -O0 -m64 -fPIC -fopenmp -pthread cu_compile_flags := -std=$(stdcpp) -w -g -O0 -m64 $(cuda_arch) -Xcompiler "$(cpp_compile_flags)" link_flags := -pthread -fopenmp -Wl,-rpath='$$ORIGIN' cpp_compile_flags += $(include_paths) cu_compile_flags += $(include_paths) link_flags += $(library_paths) $(link_librarys) $(run_paths) # 如果头文件修改了,这里的指令可以让他自动编译依赖的cpp或者cu文件 ifneq ($(MAKECMDGOALS), clean) -include $(cpp_mk) $(cu_mk) endif $(name) : $(workdir)/$(name) all : $(name) run : $(name) @cd $(workdir) && ./$(name) $(run_args) $(workdir)/$(name) : $(cpp_objs) $(cu_objs) @echo Link $@ @mkdir -p $(dir $@) @$(cc) $^ -o $@ $(link_flags) $(objdir)/%.cpp.o : $(srcdir)/%.cpp @echo Compile CXX $< @mkdir -p $(dir $@) @$(cc) -c $< -o $@ $(cpp_compile_flags) $(objdir)/%.cu.o : $(srcdir)/%.cu @echo Compile CUDA $< @mkdir -p $(dir $@) @$(nvcc) -c $< -o $@ $(cu_compile_flags) # 编译cpp依赖项,生成mk文件 $(objdir)/%.cpp.mk : $(srcdir)/%.cpp @echo Compile depends C++ $< @mkdir -p $(dir $@) @$(cc) -M $< -MF $@ -MT $(@:.cpp.mk=.cpp.o) $(cpp_compile_flags) # 编译cu文件的依赖项,生成cumk文件 $(objdir)/%.cu.mk : $(srcdir)/%.cu @echo Compile depends CUDA $< @mkdir -p $(dir $@) @$(nvcc) -M $< -MF $@ -MT $(@:.cu.mk=.cu.o) $(cu_compile_flags) # 定义清理指令 clean : @rm -rf $(objdir) $(workdir)/$(name) $(workdir)/*.trtmodel $(workdir)/demo.onnx # 防止符号被当做文件 .PHONY : clean run $(name) # 导出依赖库路径,使得能够运行起来 export LD_LIBRARY_PATH:=$(library_path_export)```empty := library_path_export := $(subst $(empty) $(empty),:,$(library_paths))解释一下,每一行什么意思,具体一些
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值