I'm trying to learn CMake, but I can't get to grips with the tutorials that are available.
Let's say my project has the structure below, and I want to make my_lib available through its CMakeLists file and use it in my main.cpp, what would my CMakeLists files look like?
├── CMakeLists.txt
├── externals
│ └── my_lib
│ └── src
│ ├── CMakeLists.txt
│ ├── MyClass.h
│ └── MyClass.cpp
└── main.cpp
Should I use include_directories or add_subdirectory?
To match the directory structure you indicated, your CMakeLists.txt files could look like this:
/CMakeLists.txt:
/externals/my_lib/src/CMakeLists.txt:
Using
PUBLIC
in thetarget_include_directories
call means that not only does your library have this as an "include path", but so does any target linking to it.The downside with this setup however is that you're also going to expose any internal headers of
my_lib
to consuming targets too. Say you also have an "Internal.h" as part ofmy_lib
which you don't want to expose. You can do this by moving the intentionally-public headers into a separate folder, e.g. "include":Your top-level CMakeLists.txt wouldn't change, but /externals/my_lib/CMakeLists.txt (which has moved up a level) now reads:
Now, since your library's "src" folder is
PRIVATE
tomy_lib
, main.cpp won't be able to#include "Internal.h"
.