I have a CMake project that is a library that also adds an example. Something like this
/example/
-> myexample.cpp
-> CMakeLists.txt
/include/
-> mylib.h
/src/
-> mylib.cpp
/CMakeLists.txt
My /CMakeLists.txt looks like this:
cmake_minimum_required (VERSION 3.16)
set(BOOST_VERSION 1.72)
option(ASIO_SEPARATE_COMPILATION "Compile Asio separately" ON)
project(mylib)
add_library(mylib STATIC "src/mylib.cpp")
target_include_directories(mylib PUBLIC "include")
if(ASIO_SEPARATE_COMPILATION)
target_compile_definitions(mylib PUBLIC -DBOOST_ASIO_SEPARATE_COMPILATION)
endif()
add_subdirectory(example)
The /example/CMakeLists.txt is as simple as it can get:
add_executable(myexample "myexample.cpp")
target_link_libraries(myexample mylib)
Note the ASIO_SEPARATE_COMPILATION option: it is there to optionally add the BOOST_ASIO_SEPARATE_COMPILATION definition. The details of what that does aren’t important in context of this question, but more can be found here for anyone interested.
Now, for whoever is using mylib, it is a good default to set ASIO_SEPARATE_COMPILATION option to ON. But for very simple executables such as myexample.cpp, it can be set to OFF for convenience. My problem is that I don’t know how to set that option only for myexample while leaving it on OFF by default for anyone else using mylib.
In other words, when mylib is used by myexample, I want mylib to be compiled with ASIO_SEPARATE_COMPILATION OFF. And when mylib is used by anyone else, I want that option to be ON by default, but configurable.
As a side note: it feels backwards that myexample is “added” from /CMakeLists.txt defining mainly the mylib library (though by looking at other projects this seems to be the standard approach). Ideally, (IMO) myexample should also showcase how an application “adds” mylibrary (not vice versa). I think doing it this other way would also solve my problem quite nicely, though I would prefer not to change the directory structure if possible.