Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to organize cmake file hierarchy with multiple optional dependencies

Tags:

cmake

I have a C++ project with a core which is basically self-contained but with a lot of interfaces to third party codes that a user may or may not want to compile. We build the code using CMake and I am now trying to organize the code a bit better.

The solution I came up with is to add to the top CMakeLists.txt file a set of options which determine whether a dependent package should be located or not.

option(WITH_FOO "Compile the interface to Foo, if found" ON)
option(REQUIRE_FOO "Require that the Foo interface to be compiled" OFF)
option(WITH_BAR "Compile the interface to Bar, if found" ON)
option(REQUIRE_BAR "Require that the Bar interface to be compiled" OFF)
...
if(WITH_FOO)
  if(REQUIRE_FOO)
    find_package(Foo REQUIRED)
  else(REQUIRE_FOO)
    find_package(Foo)
  endif(REQUIRE_FOO)
else(WITH_FOO)
  set(FOO_FOUND FALSE)
endif(WITH_FOO)

if(WITH_BAR)
  if(REQUIRE_BAR)
    find_package(Bar REQUIRED)
  else(REQUIRE_BAR)
    find_package(Bar)
  endif(REQUIRE_BAR)
else(WITH_BAR)
  set(BAR_FOUND FALSE)
endif(WITH_BAR)

Then in the the CMakeLists.txt files in the subdirectories, there will be statements such as:

if(BAR_FOUND)
  add_subdirectory(bar_interface)
endif(BAR_FOUND)

I don't particularly like this solution, partly because it is very verbose and partly because I feel that there should be some more standardized way of doing this. Is anyone aware of a better, more maintainable solution?

like image 351
Joel Avatar asked Mar 30 '12 12:03

Joel


1 Answers

Have a look at the following standard CMake modules:

  • FeatureSummary - Macros for generating a summary of enabled/disabled features
  • CMakeDependentOption - Macro to provide an option dependent on other options

Examples of using FeatureSummary (from manual):

option(WITH_FOO "Help for foo" ON)
add_feature_info(Foo WITH_FOO "The Foo feature provides very cool stuff.")

find_package(LibXml2)
set_package_properties(LibXml2 PROPERTIES DESCRIPTION "A XML processing library." URL "http://xmlsoft.org/")
set_package_properties(LibXml2 PROPERTIES TYPE RECOMMENDED PURPOSE "Enables HTML-import in MyWordProcessor")
set_package_properties(LibXml2 PROPERTIES TYPE OPTIONAL PURPOSE "Enables odt-export in MyWordProcessor")

feature_summary(WHAT ALL)
like image 145
Silas Parker Avatar answered Oct 26 '22 22:10

Silas Parker