39

For instance, how can I know if my executable target E depends on my library target L?

Let's image E depends on L1 and L2, but I don't know if they depend on L.

target_link_libraries(E L1 L2)

I'd like to get the list from CMake itself before calling target_link_libraries, so that I can do some tricks if I detect that E depends on two libraries which are incompatible. I played a bit with GetPrerequisites, but this finds out dependencies on existing libraries which are on disk, not on target which are being built.

thanks

Kevin
  • 16,549
  • 8
  • 60
  • 74
Daniel Pinyol
  • 2,094
  • 2
  • 15
  • 15
  • 4
    Just came across your question and wanted to hint to [Recursive list of LINK_LIBRARIES in CMake](http://stackoverflow.com/questions/32756195/recursive-list-of-link-libraries-in-cmake) and [Retrieve all link flags in CMake](http://stackoverflow.com/questions/34165365/retreive-all-link-flags-in-cmake). Hope this helps. – Florian Apr 03 '16 at 18:22

3 Answers3

39

You can use CMake's "dependency graphs generator". Please read this link for details

cmake --graphviz=test.dot . ...
Clare Macrae
  • 3,670
  • 2
  • 31
  • 45
Peter Petrik
  • 9,701
  • 5
  • 41
  • 65
  • 1
    To run this from within your `CMakeLists.txt` file, see this [answer](https://stackoverflow.com/a/42577803/3987854). – Kevin Jun 12 '19 at 20:36
  • 1
    It's not working on my setup, this show no dependencies (no arrow between nodes) where my code obviously have – ninjaconcombre Apr 29 '20 at 09:17
  • 4
    The ``--graphviz`` option only considers executable and library targets but *not* custom targets (as documented). So it's not always helpful. – bjhend May 07 '20 at 13:53
  • 1
    This does not answer the question as posed in the title, which is to get a _list_ of dependencies (i.e., not a graph). – definelicht Oct 25 '21 at 16:08
  • This is really helpful, thanks! – zanmato Jan 19 '22 at 18:11
11

While graphviz output likely is more intuitive, sufficiently equivalent functionality can be enabled via a simple

set_property(GLOBAL PROPERTY GLOBAL_DEPENDS_DEBUG_MODE 1)

GLOBAL_DEPENDS_DEBUG_MODE cmake.org help

LinuxDev
  • 193
  • 1
  • 7
  • Thanks! This is certainly helpful in many situations. Any chance I can make this work on a file-granularity (including header files)? – ingomueller.net Jan 19 '23 at 16:35
2

I have a top level project, which contains several external sub-projects. In the CMakeLists.txt file, most of the targets are customized and not listed in the graph by default. Looking into the document at https://cmake.org/cmake/help/latest/module/CMakeGraphVizOptions.html, and it says,

GRAPHVIZ_CUSTOM_TARGETS Set to TRUE to include custom targets in the generated graphs.

Mandatory: NO

Default: FALSE

To turn it on, write a file CMakeGraphVizOptions.cmake, and put the following line in it,

SET(GRAPHVIZ_CUSTOM_TARGETS TRUE)

Wish this helps.

user80442
  • 21
  • 2