Reputation: 341
I'm using "modern cmake" with packages and would like to get errors when target_link_libraries is missing a library.
I have one CMakeLists.txt
add_library(libB
sourceB.cpp
)
target_link_libraries(libB
PRIVATE libC
)
and this one in an other directory
add_library(libC
sourceC.cpp
)
target_include_directories(libC
PUBLIC include # Will provide include/sourceC.h
)
In sourceB.cpp, I'm including sourceC.h
Here I forget to add the add_subdirectory to libC so when I build, I get this error:
sourceB.cpp:2:10: fatal error: sourceC.h: No such file or directory
How instead of this compile time error, can I ask cmake to throw me a miss error because I specifically ask to link with libC but never gave him libC ?
I saw add_dependencies but don't necessarily want libC to be built before libB
Thanks
Upvotes: 1
Views: 627
Reputation: 141930
A simple solution is to check if it's a target. Probably somewhere on the end of your file, at least after add_subdirectory(libC)
if(NOT TARGET libC)
message(FATAL_ERROR "Och nuu, libC is not a target")
endif()
A great solution would be to implement a target_link_targets
functionality, which would allow linking only with targets. While sounds trivial, it's not so easy - static libraries can be linked circular and can be before they are defined. So you have to check if all are targets on the end of CMake file after we know every target is defined.
I did such implementation, my implementation is available here. The function k_target_link_targets
checks if all arguments are targets. From CMake 3.19.0 it uses cmake_language(DEFER
to defer execution of a checking function to the end of CMake scripts, before 3.19.0 a manual call to k_target_link_targets_check
function is needed on the end of a CMake file.
Upvotes: 2