cmake让add_subdirectory()的所有target生成到同一目录
问题描述和解决办法
整个项目包括: 库、测试程序,都是基于源码生成;测试程序肯定是executable类型了,而如果生成的库是SHARED类型,在windows下就是.dll(以及对应的.lib)文件。
执行测试程序时,出现"xxx.dll"找不到,其中"xxx.dll"是整个解决方案产生的那个共享库。
虽然可以手动复制xxx.dll到yyy.exe的目录,但是每次手动复制很低效。
方法1:设定LIBRARY_OUTPUT_PATH和EXECUTABLE_OUTPUT_PATH
需要在add_subdirectory()前设定,例如:
set(LIBRARY_OUTPUT_PATH "${CMAKE_BINARY_DIR}")
set(EXECUTABLE_OUTPUT_PATH "${CMAKE_BINARY_DIR}")
就能够分别在CMAKE_BINARY_DIR/Debug或CMAKE_BINARY_DIR/Release下得到xxx.lib和yyy.exe在一块儿了。这两个变量是全局级别的(具体到某个target,可能不起作用,见方法2)
例子1:给opencv1.0.0添加cmake支持
根目录的CMakeLists.txt如下:
cmake_minimum_required(VERSION 3.13)
project(opencv_100)
add_definitions(
-DCVAPI_EXPORTS
-DHAVE_JPEG
-DHAVE_PNG
-DHAVE_TIFF
-DHAVE_JASPER
)
include_directories(
"cv/include"
"cv/src"
"cxcore/Include"
"cvaux/include"
"otherlibs/highgui"
"otherlibs/_graphics/include"
)
link_directories("otherlibs/_graphics/lib")
set(LIBRARY_OUTPUT_PATH "${CMAKE_BINARY_DIR}")
set(EXECUTABLE_OUTPUT_PATH "${CMAKE_BINARY_DIR}")
if (CMAKE_SYSTEM_NAME MATCHES "Windows")
#message("inside windows")
# add SAFESEH to Visual Studio. copied from http://www.reactos.org/pipermail/ros-diffs/2010-November/039192.html
#if(${_MACHINE_ARCH_FLAG} MATCHES X86) # fails
#message("inside that branch")
# in VS2013, there is: fatal error LNK1104: cannot open file "LIBC.lib"
# so, we have to add /NODEFAULTLIB:LIBC.LIB
# reference: https://stackoverflow.com/questions/6016649/cannot-open-file-libc-lib
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SAFESEH:NO /NODEFAULTLIB:LIBC.LIB")
set (CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /SAFESEH:NO /NODEFAULTLIB:LIBC.LIB")
set (CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} /SAFESEH:NO /NODEFAULTLIB:LIBC.LIB")
#endif()
endif (CMAKE_SYSTEM_NAME MATCHES "Windows")
add_subdirectory("cxcore")
add_subdirectory("cv")
add_subdirectory("cvaux")
add_subdirectory("otherlibs/highgui")
add_subdirectory("samples")
# add_subdirectory("ml")
# add_subdirectory("otherlibs/cvcam")
方法2:设定target的ARCHIVE_OUTPUT_DIRECTORY和RUNTIME_OUTPUT_DIRECTORY属性
这种方法是针对特定的target来设定的。是在opencv_220/OpenCVModule.cmake
中看来的。这个版本的opencv官方配备了cmake,绝大多数模块使用define_opencv_module
宏来简化target的构建规则的编写,其定义中关于输出的库路径和可执行文件路径的设定,修改后如下(我都改成${CMAKE_BINARY_DIR}了,这样使得在VS中可以直接运行样例工程,而不至于说xxx.dll找不到):
# Additional target properties
set_target_properties(${the_target} PROPERTIES
DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}"
#ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/"
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/"
#RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/"
INSTALL_NAME_DIR "${CMAKE_INSTALL_PREFIX}/lib"
)
Greatness is never a given, it must be earned.