Under normal circumstances, each sub-project of our project is in a general project root directory, but sometimes, we need to use external folders. What should we do? For example, cxx/utility/example
within a directory CMakeLists.txt
you want to refer to the upper directory cxx/utility
: CMakeLists.txt
usually
, if cxx/utility/example
within a directory CMakeLists.txt
you use it directly.
add_subdirectory(${
CMAKE_CURRENT_SOURCE_DIR}/..)
When executed cmake -B build
, an error will be reported:
CMake Error at CMakeLists.txt:14 (add_subdirectory):
add_subdirectory not given a binary directory but the given source
directory "D:/workspace/sdk/base/cxx/utility" is not a subdirectory of
"D:/workspace/sdk/base/cxx/utility/example". When specifying an
out-of-tree source a binary directory must be explicitly specified.
Reason for error : Because the folder to be added is not a subdirectory of the current project. The last sentence points the way: to specify an external folder you must specify it explicitly. But how to specify it explicitly? Check out the official documentation.
It turns out add_subdirectory
there is another binary_dir
parameter, which is used to specify source_dir
the location in the output folder. If not specified, source_dir
the value is used. binary_dir
This must be specified if you want to add an external folder . cxx/utility/example
The changes inside CMakeLists.txt
are:
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/.. 3rdparty/base/utility)
After execution, cmake -B build
you can find additional subdirectories in the output directory , which is specified by 3rdparty/base/utility
the second parameter :binary_dir