Missing imported target

I have a folder structure like so:
/build
/src
/import
where /import contains /include and /lib folder for an imported target. /import also has a CMakeLists.txt file with following content:

add_library(my_import_target SHARED IMPORTED)
target_include_directories(my_import_target INTERFACE include)
set_target_properties(my_import_target
  PROPERTIES
  IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/lib/my_import_target.so"
)
if (TARGET my_import_target)
  message("Yay!")
endif()

Then in the /src/CMakeLists.txt file:

add_subdirectory(../import imported)
if (NOT TARGET my_import_target)
  message(FATAL_ERROR "Target not found")
endif()

The last test “fails”, i.e. my_import_target is not defined even though add_subdirectory was called just before it. What is wrong?

By default, imported targets do not have a global scope. To solve your problem, add keyword GLOBAL:

add_library(my_import_target SHARED IMPORTED GLOBAL)
1 Like