add_subdirectory() and target_link_libraries() ordering

When writing a CMakeLists.txt file, I have always called target_link_libraries() with a list of targets that I am generating in other directories, then I call add_subdirectory() to add the files that create the targets. AI is telling me that I need to call add_subdirectory() before target_link_libraries() so that the target is defined before the call to target_link_libraries() references it. I have never had an issue with target names resolving. What is the correct way to handle this?

AI does not know all, and sometime it hallucinate!

There are more ways to do it:

One is:

add_executable(your_target ...)

add_library(foo)
# ...
add_library(bar)

add_subdirectory(path/to/foo) # to use target_source(foo ...)
# ...
add_subdirectory(path/to/bar) # to use target_source(bar ...)

target_link_libraries(your_target PUBLIC foo bar ...)

I agree. It does hallucinate often. I just want to know if this is a hallucination, or it is something that I didn’t know but should have known.

Things are changing over the time. i.e.

CMake 3.12 and earlier prohibited target_link_libraries() from operating on a target defined in a different directory. If a subdirectory needed to make the target link to something, it couldn’t do so from within that subdirectory. …

from Professional CMake