[CMake] add_library and target_link_libraries in different directories?

David.Karr at L-3COM.COM David.Karr at L-3COM.COM
Mon Jan 12 16:27:54 EST 2009


> My goal would be to have
>
> -          each library in it's own directory (and a CMakeLists.txt
file
> with a add_library command)
>
> -          all dependencies stored in a single file at the root level
>
> root dependency file example:
>
>     target_link_libraries(mylib1 mylib2 mylib4)
>     target_link_libraries(mylib2 mylib2 mylib5)
>     target_link_libraries(mylib3 mylib4 mylib5)
>     . . . 

As has already been noted, the specification of target_link_libraries is
such that it can occur ONLY in the directory with the corresponding
add_library command.

What you could do is something like this:

In your "root dependency file":

    set(LINK_TO_mylib1 mylib2 mylib4)
    set(LINK_TO_mylib2 mylib2 mylib5)
    set(LINK_TO_mylib3 mylib4 mylib5)

In the CMakeLists.txt file in the directory of mylib1:

    add_library(mylib1 ...)
    target_link_libraries(mylib1 LINK_TO_MYLIB1)

So the target_link_libraries command is where it needs to be, but the
actual list of libraries to link is where you want it to be.

If you really want, I'm sure it's possible to define a macro or function
in your root configuration file, for example MyAddLibrary(lib_name
source_files), that would execute the add_library(mylib1 ...) command
and then execute the target_link_libraries(mylib1 ...) command with a
list of libraries that your root dependency file associated with mylib1.
(In fact the reason my example used variable names like LINK_TO_mylib1
was to try to make such a thing easier.)

By the way, I have a project in which I had a list of several libraries
that I wanted most of the other libraries in the project to link to.  So
I have something like this:

In the root configuration file:

    Set(MY_COMMON_LIBRARIES mylib6 mylib7 mylib8)

In the directory of some other library such as mylib1:

    add_library(mylib1 ...)
    target_link_libraries(mylib1 ${MY_COMMON_LIBRARIES} mylib2 mylib3)

This lets me add or subtract library dependencies from a lot of targets
all at once by editing just the root configuration file ... not exactly
what you asked for, but somewhat similar.

David



More information about the CMake mailing list