Qartar
Qartar

Reputation: 430

How can I include directories with project relative paths in CMake?

I am developing a product with a team using CMake. We have several Visual Studio projects (libraries and executables) inside of our CMake project which reference other project headers (via target_include_directories()). In a source file these header includes look like:

#include "some_header.h"    // from project_x
#include "another_header.h" // from project_y

I'd like to be able to include these headers with paths that reference the project they are pulled from, e.g.:

#include "project_x/some_header.h"
#include "project_y/another_header.h"

What is the most acceptable way to do this? I have thought of a couple solutions:

  1. Add the directory which contains the project as an include path. This has the undesirable side-effect of including everything and seems like a bad solution.

  2. Include a subfolder of the project called 'include' which contains a folder named with the same as the project, which creates a slightly redundant path: /<project_name>/include/<project_name>/<...>

There is a third solution, to use a shared include directory with a subfolder for each project, but it will not work for our project because we group our build projects by category in the file system and Visual Studio solution and it will cause the folder structure inside of /include/ to diverge from the rest of source tree which is undesirable.

Are there any better (or more canonical/idiomatic) ways to accomplish this?

Upvotes: 1

Views: 1426

Answers (1)

huu
huu

Reputation: 7482

If you have a project structure like this:

project_x/some_header.h
project_y/another_header.h

and you want to keep all of your CMakeLists the same, then I would introduce another folder in each project:

project_x/project_x/some_header.h
project_y/project_y/another_header.h

Of course, this requires changing the includes in each project to reflect this new structure, including the project where the header is defined proper.

There's some precedence to this, as this is how curl and googletest do it.

Edit: I understand this is very similar to the second approach you outlined. If your directory structure already employs include directories, then my suggestion is exactly the same as your second one. At the very least, this should confirm your intuition that this isn't an entirely absurd thing to do, even if it creates some redundancy.

Upvotes: 1

Related Questions