NoSenseEtAl
NoSenseEtAl

Reputation: 29996

Force CMake target_link_libraries to fail when adding nonexistent target

CMake has an irritating default (I presume, I see nothing magical in my CMake config, but I could be wrong since I know very little about CMake) behavior that he silently ignores when you add a target to your project even if that target does not exist, for example:

project(StackOverflow)

// another CMakeLists.txt

project (Stuff)

target_link_libraries(Stuff PUBLIC StackOverlow )

Is there a way to force CMake to check that all projects you link in target_link_libraries must exist?

Upvotes: 9

Views: 4005

Answers (2)

lgisler
lgisler

Reputation: 51

It is possible for CMake to fail if you link ALIAS targets. For example

In first CMakeLists.txt

add_library(StackOverflow STATIC lib.cpp)
add_library(StackOverflow::StackOverflow ALIAS StackOverflow)

In second CMakeLists.txt

target_link_libraries(Stuff PUBLIC StackOverflow::StackOverflow)

CMake will fail with an error if StackOverflow::StackOverflow is not defined.

https://cmake.org/cmake/help/v3.0/manual/cmake-buildsystem.7.html#alias-targets

Upvotes: 5

Kevin
Kevin

Reputation: 18243

In CMake, you do not link projects to other projects. Instead, you link targets to other targets.

CMake targets are only created via a few commands (such as add_library, add_executable, and add_custom_target). The project command does not create a CMake target, it merely declares a project.

Furthermore, the target_link_libraries() command accepts the following arguments after the scoping keyword:

  • A library target name
  • A full path to a library file
  • A plain library name
  • A link flag
  • A generator expression
  • A debug, optimized, or general keyword

It does not accept project names, although if you put a project name, it will instead look for a CMake target or library file on your system with that name.

To get to the root of what I believe you're asking: If you provide link-item name to target_link_libraries() that does not match an existing target, the command will simply search for a library file of that name instead.

To check if a target exists before trying to link it, you can do:

if (TARGET StackOverflow)
    target_link_libraries(Stuff PUBLIC StackOverflow)
endif()

I suggest reading through the linked target_link_libraries() documentation if you want more details about what this command does.

Upvotes: 1

Related Questions