Search code examples
cmakecmakelists-options

CMakeLists.txt Error. - "add_subdirectory(source) - given source "source" which is not an existing directory". I am new to CMake struggling with this


This is my CMakeLists.txt file

cmake_minimum_required (VERSION 3.10)
project (hello DESCRIPTION "HELLO WORLD" VERSION 20.05.05)

option (TARGET_ONE "Build for Target One" OFF)

set (CMAKE_CXX_STANDARD 14)
set (CMAKE_CXX_STANDARD_REQUIRED ON)
set (CMAKE_POSITION_INDEPENDENT_CODE ON)

if (TARGET_ONE)
    add_definitions (-DTARGETONE)
endif()

add_subdirectory (source)

EDIT: This is the command I am using:

cd ~/build
CMAKE_FLAGS="CXX -DTARGET_ONE=ON -DCMAKE_BUILD_TYPE=Release" cmake .
~/build cmake --build .

enter image description here


Solution

  • It seems like you are calling CMake for the wrong directory.

    Given a project directory <project_dir> that contains your CMakeLists.txt and a subdirectory source you can call CMake as follows:

    cmake -S <project_dir> -B <build_dir> -DCMAKE_BUILD_TYPE=Release -DTARGET_ONE=ON
    cmake --build <build_dir> --target all --config Release
    

    CMake will create the directory <build_dir> if it does not exist.

    Languages CXX and C are activated by default if no LANGUAGES argument is used in the project command.

    If your CMake version is less than 3.13 it does not understand the -S option and has a different usage of the -B option. But it has undocumented options -H and -B. The call then looks like this (no space after -H and -B options!):

    cmake -H<project_dir> -B<build_dir> -DCMAKE_BUILD_TYPE=Release -DTARGET_ONE=ON