Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake: Best method for "subprojecting" files

Tags:

cmake

I'm learning/vetting CMake at the moment as I'm thinking of migrating our code to it. One thing we do a lot of with our current make system is to "subproject" common code files. For example, we have a lot of shared, generic headers (plus some c/cpp files) which get included in every project we create. I want to replicate this in CMake but I don't see an easy way of doing it. To be precise, I want to do something like:

Parent CMakeLists.txt

add_subdirectory(shared_folder shared_build_folder)

#Next line should somehow add in the files reference in the shared_folder
add_executable([specific files for this project] build_folder)

Child CMakeLists.txt (shared_folder)

#Somehow have a list of files here that get added to the parent project

So far I've found various "ways" of doing this, but all seem a little hacky. I'm coming to the conclusion that this is in fact the way I have to do things and CMake isn't really geared towards this style of development. For clarity, most of my solutions involve doing something like creating a variable at the parent level which consists of a list of files. This variable (via some shenanigans) can get "passed" to/from any children, filled in and then when I call add_exectuable I use that variable to add the files.

All my solutions involve quite a few macros/functions and seemingly quite a bit of overhead. Is this something other people have tried? Any clues on the best approach for doing this?

Thanks Andrew

like image 252
Andrew Parker Avatar asked Dec 07 '25 13:12

Andrew Parker


1 Answers

We were facing the exact same problem and after some time of crying we accepted the CMake-way and it resulted in a better structured project even if it meant to change some parts of our structure.

When using sub-directories the targets are automatically exported throughout the whole project (even in subsequent other add_subdirectory-calls) once the add_subdirectory-statement was processed: sub-projects which contain common code are creating libraries.

There is also the PARENT_SCOPE which you can use to export variables to parent CMakeLists.txt

For "other" things we simulated the FindPackage-mechanism by including .cmake-files into the main CMakeLists.txt with include. In doing so we can provide variables easily, change the include_directories and do other fancy things global to the project.

As there are no dependencies between cmake-variables, we don't use cmake to configure the source (features of the project), but only the build (compiler, includes, libraries...). This split was the key element of our build-system-refactoring.

like image 122
Patrick B. Avatar answered Dec 10 '25 20:12

Patrick B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!