How to print variables in CMake?

Viewed 8108

I want to use cmake to build my project, my CMakeLists.txt is very simple:

cmake_minimum_required(VERSION 3.20)

 project(YuvParallelProcess)

 message("$(PROJECT_SOURCE_DIR)")

 include_directories($(PROJECT_SOURCE_DIR)/inc)
 link_directories($(PROJECT_SOURCE_DIR)/lib/libyuv)

 add_executable(YuvParallelProcess  $(PROJECT_SOURCE_DIR)/src/main.cpp)

 target_link_libraries(YuvParallelProcess  libyuv.a)

my project files are organized as follows:

 YuvParallelProcess
                      build
                      data
                      inc
                      lib
                      src
                      CMakeLists.txt

when I run cmake .. in build directory, the shell prints:

$(PROJECT_SOURCE_DIR)
-- Configuring done
CMake Error at CMakeLists.txt:10 (add_executable):
  Cannot find source file:

    $(PROJECT_SOURCE_DIR)/src/main.cpp


CMake Error at CMakeLists.txt:10 (add_executable):
  No SOURCES given to target: YuvParallelProcess

I don't know why the shell just prints $(PROJECT_SOURCE_DIR) other than the value of PROJECT_SOURCE_DIR How can I print the value of PROJECT_SOURCE_DIR By the way, I can't figure out why cmake failed to compile my project

2 Answers

Cmake uses curly braces for getting values of variables:

${PROJECT_SOURCE_DIR}

I suggest to dump messages like below to not skip empty messages.

message(PROJECT_SOURCE_DIR="${PROJECT_SOURCE_DIR}")

Cmake failed to configure your project because it did not recognise variables in parentheses and considered $(PROJECT_SOURCE_DIR) to be a string literal as is.

There is CMakePrintHelpers Cmake module for dumping variables exactly like above.

include(CMakePrintHelpers)
cmake_print_variables(PROJECT_SOURCE_DIR)

Instead of using message, you can also use cmake_print_variables to display variables. in this case, you must include CMakePrintHelpers

include(CMakePrintHelpers)

cmake_print_variables(PROJECT_SOURCE_DIR)

The ouput will be :

-- PROJECT_SOURCE_DIR="path/to/your/project"

With cmake_print_variables you can also display several variables, like this:

cmake_print_variables(PROJECT_SOURCE_DIR ANOTHER_VARIABLE)

The ouput will be :

-- PROJECT_SOURCE_DIR="path/to/your/project" ; ANOTHER_VARIABLE="other variable"
Related