[CMake] Does target order matter for dependencies?

Nils Gladitz nilsgladitz at gmail.com
Thu Dec 8 10:16:41 EST 2016


On 12/08/2016 04:01 PM, Robert Dailey wrote:

> When I define my targets (custom, library, executable), does the order
> of their declaration matter when it comes to using those targets in
> dependencies? It's difficult to explain, so I'll show an example:
>
>
> add_executable(foo main1.cpp)
> target_link_libraries(foo abc)
>
> add_library(abc main2.cpp)
>
> In the example above, the add_library() happens after
> target_link_libraries() for the executable. I've seen this work, but I
> was using static libraries. Would this work for shared libraries too?

Yes, that is fine.

> Does CMake do a multi-pass parse so that all targets are known prior
> to them being referenced?

The link-dependencies are evaluated at generation time after your cmake 
code has been fully parsed.
At that time all targets are known.

>
> The target_link_libraries() [1] documentation states:
>
> "The named target must be created by add_library() within the project
> or as an IMPORTED library. If it is created within the project an
> ordering dependency will automatically be added in the build system to
> make sure the named library target is up-to-date before the <target>
> links."
>
> I'm not sure what "up-to-date" here means, or if this specific
> documentation is talking about compile-time dependencies or cmake
> dependencies.

It means CMake makes sure the generated build system fully builds "abc" 
before it starts building "foo" (which isn't always strictly required 
but how it is currently implemented).

e.g. if "abc" has custom commands that generate header files that "foo" 
also depends on this will make sure they are created/updated before 
"foo" makes use of them.

And more obviously "abc"'s library output is created/updated before 
"foo" tries to link to it.

Nils


More information about the CMake mailing list