Eclipse CDT动态库Shared Library…

来源:互联网 发布:面试linux运维故障处理 编辑:程序博客网 时间:2024/05/29 10:41
    对于建立SharedLibrary,其实很简单,就是建立工程的时候选择Shared Library。
想必很多朋友都希望在eclipse中编译好动态库以后能在我们的程序中直接调用,并且不需要在调用程序(这里以test为例,库工程名为mylib)中去配置环境变量LD_LIBRARY_PATH,或者在gcc编译时指定路径名(该方法也不错,很适用较少库文件的引用)

  -R${workspace_loc:/mylib/Debug}

    调用我们编译好的库有两步:

   1.增加包含目录,在workspace中将需要的库包含进来

Eclipse <wbr>CDT动态库Shared <wbr>Library配置与使用,解决找不到.so的问题

   2.添加动态库名和库的路径

Eclipse <wbr>CDT动态库Shared <wbr>Library配置与使用,解决找不到.so的问题

    现在说下环境变量,使用LD_LIBRARY_PATH变量,选中project右键-> run as -> run configuration-> Environment,add一个,name为LD_LIBRARY_PATH,value为${workspace_loc:/mylib/Debug},

Eclipse <wbr>CDT动态库Shared <wbr>Library配置与使用,解决找不到.so的问题

   这样程序能在eclipse中运行了,但我们想到终端运行却还是"error while loading sharedlibraries:...",要在终端运行,需要设置该坏境变量(#exportLD_LIBRARY_PATH=/root/workspace/mylib/Debug/),很是不爽。

    方法二:先看一段英文:
    Onelink option you might use is ld's ``rpath'' option, which specifiesthe runtime library search path of that particular program beingcompiled. From gcc, you can invoke the rpath option by specifyingit this way:
 -Wl,-rpath,$(DEFAULT_LIB_INSTALL_PATH)
Ifyou use this option when building the library client program, youdon't need to bother with LD_LIBRARY_PATH (described next) otherthan to ensure it's not conflicting, or using other techniques tohide the library.

   所以我们可以在test中设置中加入一段,即工程Property -> C/C++build -> settings -> GCC CLinker-> Miscellaneous -> Link flags中添加-Wl,-rpath=/root/workspace/mylib/Debug,可完美编译哦...

   另外一种让人比较满意的方法三:在工程Property -> C/C++ build-> settings -> GCC CLinker-> Miscellaneous-> other option 中添加

-R"${workspace_loc:/mylib/Debug}" 

Eclipse <wbr>CDT动态库Shared <wbr>Library配置与使用,解决找不到.so的问题

   该方法很不错。是编译阶段做好连接工作,而且可在终端执行(./test)

    我使用的方法四:主要是通过配置文件做好一些准备工作后,直接引用lib*.so文件
由于Linux动态库的默认搜索路径是/lib和/usr/lib64等类似的目录,如果在这些地方找不到会按照配置文件/etc/ld.so.conf中指定的目录查找,所以我们可以在/etc/ld.so.conf.d目录下创建*.conf(如workspace.conf)配置文件,用来指定我们希望被查找到的lib*.so,如往里写入/root/lib,随自己喜欢,方便管理就好。

    在程序运行时,此目录便会被搜寻,我们可以将build好的lib*.so软连接到此,
#cd /root/lib/,
#ln -s /root/workspace/mylib/Debug/libmylib.so .
#ldconfig
    这样设置好以后,可以很方便的管理,更重要的是我们再次调用库时就像调用系统的库一样,直接使用,不需要再去针对每一个调用程序做配置,感觉最爽对很多完美主义的朋友是很重要的。 
#cd /root/workspace/test/Debug/
#ldd test
       libmylib.so =>/root/lib/libmylib.so (0x00002b5f040f3000)
       libc.so.6 => /lib64/libc.so.6(0x0000003829a00000)
       /lib64/ld-linux-x86-64.so.2(0x0000003828a00000)


原创粉丝点击