Sorry for mixing that up over and over again. There are two different ways - either depending on an explicit target or on a variable which contains target names.

In both cases the target might not exist or the variable might be empty. That is the case when the other package has already been installed and is not part of the current CMake context.

Therefore you need to check in both case if you depend on target from other packages:

    if(TARGET ublox_msgs_generate_messages_cpp)
      add_dependencies(ublox_gps ublox_msgs_generate_messages_cpp)
    endif()

    if(ublox_msgs_EXPORTED_TARGETS)
      add_dependencies(ublox_gps ${ublox_msgs_EXPORTED_TARGETS})
    endif()

If you do depend on a dependency withing the same package you do not need the check for empty/target existance since you "know" that your package has messages.