[Cmake] Subdirs and Dependecies.

Brad King brad.king at kitware.com
Sat Jul 24 19:39:28 EDT 2004


Ulrik Mikaelsson wrote:
> atuin/CMakeLists.txt contains:
> SUBDIRS( share base )
> ADD_EXECUTABLE( slicker slicker.cpp sources_moc)
> TARGET_LINK_LIBRARIES( slicker slicker_base slicker_share )
 >
> atuin/share/CMakeLists.txt contains:
> - ------------------------------
> ADD_LIBRARY( slicker_share SHARED slicker_share_sources slicker_share_moc)
 >
> When running cmake on this setup, I get the error:
> Library slicker_base is defined using ADD_LIBRARY after the library is used
> using TARGET_LINK_LIBRARIES for the target slicker. This breaks CMake's
> dependency handling. Please fix the CMakeLists.txt file.
> 
> I've tried to move the SUBDIRS-directive up and down in the top CMakeList, but
> without result. What should I do? Have I done something wrong, and if so,
> what?

There are two parts to this answer:

1.) CMake automatically tracks dependencies of one library linking to 
another so that whenever an executable is linked to a library all the 
dependent libraries are pulled in automatically.  In order to do this 
correctly, library targets must exist before they are linked.

2.) The SUBDIRS command does not immediately proceed into a 
subdirectory.  Instead it tells CMake to process the subdirectories 
after it finishes with the current directory.  Therefore even though the 
SUBDIRS command comes before the ADD_EXECUTABLE command, the 
ADD_EXECUTABLE and TARGET_LINK_LIBRARIES commands are processed before 
the ADD_LIBRARY commands for your libraries are ever seen.

The solution to your problem is to move the executable into a third 
subdirectory:

# CMakeLists.txt
SUBDIRS(base share exe)

# base/CMakeLists.txt
ADD_LIBRARY(slicker_base ...)

# share/CMakeLists.txt
ADD_LIBRARY(slicker_share ...)

# exe/CMakeLists.txt
ADD_EXECUTABLE(slicker ...)
TARGET_LINK_LIBRARIES(slicker slicker_share slicker_base)

Alternatively you can add both libraries and the executable in the 
top-level CMakeLists.txt file and use relative paths to refer to the 
sources in the subdirectories.

-Brad


More information about the Cmake mailing list