Lookup rules differ for deferred import targets based on the GLOBAL flag
target_link_libraries
allow you to reference non-existent targets. The lookup rules for those targets differ based on if they they are finally constructed as imported local scope vs imported global scope.
CMakeLists.txt
cmake_minimum_required(VERSION 3.23 FATAL_ERROR)
project(target_lookup)
add_subdirectory(subdirA)
add_library(later STATIC empty.cpp)
add_library(to_be_created::alias ALIAS later)
add_library(to_be_created::imported IMPORTED INTERFACE)
add_library(to_be_created::imported_global IMPORTED INTERFACE GLOBAL)
add_executable(main main.cpp)
target_link_libraries(main PRIVATE common_interface)
subdirA/CMakeLists.txt
add_library(common_interface INTERFACE)
target_link_libraries(common_interface INTERFACE
to_be_created::alias to_be_created::imported_global to_be_created::imported)
We would expect all 3 to_be_created
targets to be found when main uses common_interface
since they exist at that point. But the lookup of local targets for common_interface
is based on a snapshot of when the target was created, and doesn't redo the search based on the local variable snapshot of main
.