Relative linking order with transitive imported targets
My problem:
The linking order of static libraries is wrong: dependency is listed before the target
My setup:
- I load
CUDA
as an imported target into my project (lines 3-8) - I have a prebuilt library
opencv
that depends onCUDA
. I load opencv as an imported target into my project (lines 9-13) - I build an executable that links against both
CUDA
andopencv
- I have a problem with the relative order of libs in the final linking command. I was expecting the resulting
link.txt
to listCUDA
afteropencv
.
The generated link.txt:
/usr/bin/c++ CMakeFiles/cmake_bin.dir/main.cpp.o -o cmake_bin .../libcudart_static.a .../libcusparse_static.a .../libopencv_world.a
The expected link.txt:
/usr/bin/c++ CMakeFiles/cmake_bin.dir/main.cpp.o -o cmake_bin .../libopencv_world.a .../libcudart_static.a .../libcusparse_static.a
The latter link.txt was expected since I add a dependency from opencv on cuda (line 13). This is my CMakeLists.txt (the numbers in front are supposed to indicate line-numbers)
1 | cmake_minimum_required(VERSION 3.9)
2 | project(cmake_test)
3 | add_library(cudart STATIC IMPORTED)
4 | set_target_properties(cudart PROPERTIES IMPORTED_LOCATION "/usr/local/cuda/lib64/libcudart_static.a")
5 | add_library(cusparse STATIC IMPORTED)
6 | set_target_properties(cusparse PROPERTIES IMPORTED_LOCATION "/usr/local/cuda/lib64/libcusparse_static.a")
7 | add_library(cuda INTERFACE)
8 | target_link_libraries(cuda INTERFACE cudart cusparse)
9 | add_library(opencv_lib UNKNOWN IMPORTED)
10 | set_target_properties(opencv_lib PROPERTIES IMPORTED_LOCATION "/home/.../libopencv_world.a")
11 | add_library(opencv INTERFACE)
12 | add_dependencies(opencv cuda)
# expressing dependency from opencv to cuda
13 | target_link_libraries(opencv INTERFACE opencv_lib cuda)
14 | add_executable(cmake_bin ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
# depend on both cuda and opencv for the binary. note that opencv depends on cuda itself.
15 | target_link_libraries(cmake_bin PUBLIC cuda opencv)
If I replace line 15 by the following line I get my expected result
target_link_libraries(cmake_bin PUBLIC opencv)
In this case opencv is listed before cudart and cusparse in the link.txt. However, I cannot omit cuda from the executable in my real-case scenario. I have been trying so many different approaches but I cannot get the transitive dependency to work. I would highly appreciate a small hint into the right direction. Many Thanks!