Cmake building two projects

Viewed 168

I want to build two projects using cmake (A library and sandbox application using that library).

I'm currently having the following folder structure:

-- yanthra_engine
 |
  -- CMakeLists.txt
  -- lib
  -- ...
-- sandbox
 |
  -- CMakeLists.txt
  -- out
  -- ...

The yantra_engine builds a library where as sandbox builds an executable(using the above mentioned library). Should I keep full fledged CMakeLists files for both the projects? Is there any efficient folder structure to follow?

I would like the library to build automatically when building my sandbox application, but not vice-versa.

2 Answers

You should keep seperate CMakeLists.txt files. It's good practice to use one CMakeLists.txt file per unrelated target. (Unrelated in the sense of not being different builds of the same library, e.g. one shared one static.)

Whether to add both targets to the same project is basically up to you. If the library is properly set up, you could create a seperate project for the library and use it's install target to install the library including cmake configuration files on your machine making it easy to import the installed library as a target to the sandbox project. This requires you to add the appropriate install commands to the library.

If you want to be able to build both the library and the sandbox via the same build files, basically all you need to do is to make sure both CMakeLists.txt files are reachable from a CMakeLists.txt file.

Without location of any of the files you could e.g.

  1. Create a CMakeLists.txt file in the parent folder adding both subdirectories
cmake_minimum_required(VERSION 3.0)

project(CommonProject)

add_subdirectory(yanthra_engine)
add_subdirectory(sandbox EXCLUDE_FROM_ALL) # targets in sandbox not built by default.
  1. You could also include the yanthra_engine directory from sandbox/CMakeLists.txt
...
add_subdirectory(../yanthra_engine "${CMAKE_BINARY_DIR}/yanthra_engine_build")
...

Both approaches allow you to either set up a build project for the lib on its own or set up a build project for both. In approach 1 the source directory for building both would be the parent directory of yanthra_engine and sandbox and in approach 2 it would be sandbox.

For both approaches you don't need to wory about unnecessarily building the sandbox project though as long as you specify the target you want to build. Since sandbox links the lib but there is no dependnecy established the other way round building sandbox makes sure the lib is up to date, but building the lib only builds the lib and its dependencies which excludes the sandbox.

One thing you can try is to let yanthra be a subdirectory of sandbox. Then you can do this in sandbox:

add_subdirectory(yanthra_engine)

Related