Behavior of target_link_libraries when target is a static lib

Hi, I’m using CMake 3.29.0-rc3 with the Ninja generator on Windows with MSVC. I have the following CMakeLists.txt:

cmake_minimum_required(VERSION 3.29.0 FATAL_ERROR)

project(test C)

add_library(my_lib STATIC my_lib.c)

target_link_libraries(my_lib PUBLIC something_that_does_not_exist)

I see that I’m able to configure and build the project without any errors, even though something_that_does_not_exist is set as a dependency of my_lib. I presume this will error out at the build stage if I try to link, say, an executable against my_lib, but I wonder whether it would be better to have CMake itself emit an error when it realizes that a target depends on something that doesn’t exist.

I don’t think that’s doable. Remember that target_link_libraries() also accepts plain library names (not just CMake target names) as arguments, and passes these in a platform-appropriate way to the linker. To signal an error for non-existent things, CMake would have to recreate (each) linker’s search process. Plus it’s possible that the library will be somehow made available (e.g. downloaded) by an earlier build step, so a CMake error is definitely not always appropriate in this case.

It is possible in CMake 3.23 and higher. See

1 Like

Ah, very interesting. Thanks for the response.

@Angew is there a catch to this that I’m not seeing, or is @vardarirrgan1’s answer correct? Thanks.

I believe it’s correct. I wasn’t aware of LINK_LIBRARIES_ONLY_TARGETS’s existence when I answered.

I suppose the catch is that it is pretty new. :wink:

1 Like