CMake: Common dependency between different projects

Hello!

I have a question regarding a project (C++, CMake) I am working on. Let’s assume the following simplified project structure for demonstration purposes (each folder contains some source and header files):

demo_project
|
|–hal
|
|–util

Both demo_project and hal depend on util. For now I am using a simple Modern CMake approach where I use target_sources so that I “push” the dependencies on the target demo_project.

/* Example of util’s CMakeLists.txt */
target_sources(demo_project
PUBLIC
#some util files
PRIVATE
#some util files
)

With this approach, hal does not need to take into cosideration that it needs some files from util in its CMakeLists.txt.

The key idea now is that hal could be later built as an independent library (a standalone project) which could be used in different projects. So I would like a project structure like the following:

demo_project
|
|–hal
| |
| |–util
|
|–util

So that I can later take hal and incorporate it in a different project which may not depend on util.

new_project
|
|–hal
| |
| |–util
|
|–foo

The problem is that I don’t want demo_project which depends on util, and hal to use a separate copy of util. I want them both to use the same copy of util.

I cannot leave the util folder only inside hal. The problem with this approach is that if for some reason hal was replaced by another implementation, e.g. hal2 which did not depend on util, the project would not built.

I could make the assumption that in both cases util is placed in the same level with hal. In this case for
a project (let’s call it demo_project) that depends on util, I would have to do the following:
/* CMakeLists.txt of demo_project */
add_subdirectory(hal)
add_subdirectory(util)

/* CMakeLists.txt of hal */
add_subdirectory(…/util)

But this approach seems a little bit “ugly” to say the least. And I am not sure what happens in this case, that both demo_project and hal add the same CMakeLists.txt file.

Could you provide any feedback or suggest an alternative better approach?

Disclaimer: I am new to CMake, hope I described my problem well! Let me know if you need more info! Thanks in advance!

hal can ship its own util, but it should have an option to say "I brought my own util" and give it the information it needs to consume it (basically the targets I assume). The combining project(s) can then just set up hal to build to match its structure.

Cc: @craig.scott