Is there a way to specify what methods a library contains in CMake?

Viewed 33

I have a CMake project where I'm using some options to control what the final library actually implements. Something like this (in pseudo-code):

// CMakeLists.txt
option(ADD_BAR "Include the bar methods" ON)
configure_file(...)
add_library(foo SHARED foo.cpp)

// foo.cpp
void doFoo(){
  ...
}
#ifdef ADD_BAR
void bar(){
  ...
}
#endif

Then, I have other targets that link against this library. Is there a way in CMake I can detect whether bar() exists in the final libfoo.so or that this target was compiled with this option disabled? Basically, I'd like to propagate the information about how the library was compiled (e.g. with what enabled options) so I can skip downstream targets that consume it but need unsupported features.

1 Answers

First, let's have a macro that produces a bit of code that checks whether a symbol was defined, and adds a relevant macro definition for the compiler:

macro (add_definition_if_var symbol)
  if (${symbol})
    add_compile_definitions (${symbol})
  endif ()
endmacro ()

Then, it's as easy as:

option (ADD_BAR "Include the bar methods" ON)
add_definition_if_var (ADD_BAR)

And, if ADD_BAR was set to ON, the ADD_BAR macro will be defined within your library project :)

If you have many such options, you could do it all in one go:

function (defining_option var description state)
  option (${var} "${description}" ${state})
  if (${var})
    add_compile_definitions (${var})
  endif ()
endfunction ()


defining_option (ADD_BAR "Include the bar methods" ON)
defining_option (ADD_FROB "Frobnicate" OFF)
Related