在mac某机器中cmake生成makefile文件的时候,发现提示如下:

....
CMake Warning (dev):
  Policy CMP0042 is not set: MACOSX_RPATH is enabled by default.  Run "cmake
  --help-policy CMP0042" for policy details.  Use the cmake_policy command to
  set the policy and suppress this warning.

  MACOSX_RPATH is not specified for the following targets:

   cjson
   iniparser
   stemmer
   word2vec

This warning is for project developers.  Use -Wno-dev to suppress it.

-- Generating done
....

而之前在linux下这组CMakeLists.txt文件一直很好的工作,不知为何突然出来这个warning了. 简单的google了一下,立刻发现其实这是2.8.2就有的更新了,为了针对mac下搞的安装lib库各种奇怪的位置而弄的一些fix. 维护者Kitware的一个说明可以看这里.作者各种介绍了OSX中的各种存放到rpath的逻辑,查看详细内容各位可以直接看原文,我直接说需要做的一些修改.

...... 现在我们知道@rpath是怎么工作以及它为何是一个好东西了,现在我们用一个简单的例子来说明如何使用它. 可以注意到的是,目标属性是MACOSX_RPATH和INSTALL_RPATH,MACOSX_RPATH是一个简单的开关来决定@rpath 是否被使用.在之前,INSTALL_NAME_DIR被用来控制决定安装的名字,但此时我们不再这样使用,若此时依然被使用,它会覆盖MACOSX_RPATH标记,方便起见,我们可能还是设置CMAKE_MACOSX_RPATH的值来覆盖多个目标

例子如下

cmake_minimum_required(VERSION 2.8.12)
project(OSXRPath) 
 
# enable @rpath in the install name for any shared library being built
# note: it is planned that a future version of CMake will enable this by default
set(CMAKE_MACOSX_RPATH 1)
 
# add a shared library
add_library(foo SHARED foo.cpp)
 
# add an executable
add_executable(bar.cpp)
# use the shared library
# note: CMake will automatically add an RPATH to this executable which 
#   is the absolute location of libfoo.dylib in the build tree.
target_link_libraries(bar foo)
 
# installation
install(TARGETS foo DESTINATION lib)
install(TARGETS bar DESTINATION bin)
 
# the install RPATH for bar to find foo in the install tree.
# if the install RPATH is not provided, the install bar will have none
set_target_properties(bar PROPERTIES INSTALL_RPATH "@loader_path/../lib")

我们通过高亮的第六行设置CMAKE_MACOSX_RPATH启用其feature即可.

博客中还提到,为了更方便的debug,有如下几个tips

  • 查看一个shared library的install name , 可以使用命令"otool -D <file>"
  • 查看一个shared library依赖库的install name , 可以使用命令 "otool -L <file>"
  • 查看用@rpath的shared library依赖的RPATHs位置,使用"otool -l <file> | grep LC_RPATH -A2"
  • 修改RPATHs可以使用-rpath, -add_rpath,和 -delete_rpath.参数

Yu

Ideals are like the stars: we never reach them, but like the mariners of the sea, we chart our course by them.

Leave a Reply

Your email address will not be published. Required fields are marked *