将libyuv作为三方库编译存在的问题

 

将libyuv作为三方库引入主项目后,在install阶段会出现找不到文件的问题。

问题描述

笔者在主项目中引入libyuv作为三方库,使用add_subdirectory(libyuv)的方式引入,然后在install阶段会出现找不到文件的问题,具体问题如下:

CMake Error at thirdparty/libyuv/cmake_install.cmake:41 (file):
  file INSTALL cannot find
  "/home/<username>/ws/fsbuild/idps_perception_node/yuvconvert": No such
  file or directory.

问题分析

libyuv/CMakeLists.txt 中,有如下代码:

# install the conversion tool, .so, .a, and all the header files
INSTALL ( PROGRAMS ${CMAKE_BINARY_DIR}/yuvconvert			DESTINATION bin )
INSTALL ( TARGETS ${ly_lib_static}						DESTINATION lib )
INSTALL ( TARGETS ${ly_lib_shared} LIBRARY				DESTINATION lib RUNTIME DESTINATION bin )
INSTALL ( DIRECTORY ${PROJECT_SOURCE_DIR}/include/		DESTINATION include )

这里的 ${CMAKE_BINARY_DIR} 是主目录的 build 目录(具体目录可以自己指定),而不是 libyuvbuild 目录,所以在 install 阶段会找不到 yuvconvert 文件。

解决方案

INSTALL ( PROGRAMS ${CMAKE_BINARY_DIR}/yuvconvert			DESTINATION bin )

改为

INSTALL ( PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/yuvconvert			DESTINATION bin )

这样在找yuvconvert文件时就会在 libyuvbuild 目录下找到文件。

对 install 命令的进一步理解

cmake 官方对 install 的解释:

This command generates installation rules for a project. Install rules specified by calls to the install() command within a source directory are executed in order during installation.

也就是说通过调用 install() 命令,可以为项目生成安装规则。其实这个规则最终会写到每个(主/子)项目 build 目录下的 cmake_install.cmake 文件中,然后在 make install 时执行这个文件,将文件拷贝到指定的目录。

而拷贝到哪个目录,这个前缀就是由 CMAKE_INSTALL_PREFIX 指定的。