JPalomino JPalomino - 28 days ago 9
C++ Question

Cmake - Library with multiple projects

In my team we made some applications using C++ as main language and when a new project arrives we always end in copy-pasting other project's files when needed . It's frequent and we had a discuss to make an improvement.

So, in order to change that we decided to make an unique library (or many little libraries) that contains everything that is not of the business itself. And we decided to use cmake for that.

But, my question is if is there a way to import this library or these little libraries without compiling them everytime we commit a change.

For example if we have two libraries and two projects, where:


  1. Project A depends on -> library A and Library B

  2. Project B depends on -> library B only



Having our source directory like this:


  • LIB A


    • include

    • src

    • CMakeLists.txt


  • LIB B


    • include

    • src

    • CMakeLists.txt


  • Project A


    • include

    • src

    • CMakeLists.txt


  • Project B


    • include

    • src

    • CMakeLists.txt




How can we set CmakeLists in project A and B so, when we change something in Library A or B, and re-run cmake and then make in project B for example, all of changes apper in it. And the same for the other project ?.

Is it possible ?

Answer Source

I had the same issue in the past while working on some personal project.

I can offer some suggestions, some of which use your approach towards solving the problem, and some of which don't:

Method 1 (A different approach, multiple source control repositories)

Don't split the code using different CMake files. Instead, use a single CMake file and split the codebase into smaller repositories.

For example, all the shared utility libraries altogether could've been a single repository, while application A and B, get a repository each. (You could of course split the utility libraries into multiple repositories as well).

This makes sure that you don't have to hold/update/work with all the projects at once, but only those you actually need. The only downside, is that you have a constrain on the way you checkout these projects, but I don't think it's an issue.

Method 2 (Same approach, using CMake's add_dependencies)

You could define dependencies on the compilation of applications A and B so that the relevant libraries are automatically built if they were updated.

Here is a link to CMake's add_dependencies manual.