CMake How to check target for build

Denis Kotov picture Denis Kotov · May 9, 2017 · Viewed 7.8k times · Source

I have tried to find solution: How to check target for build ?

Consider the following CMake script:

cmake_minimum_required(VERSION 3.5.1)
project(cppTests)

# How to check at this point the target of build
if(TARGET "cppTests")
    message(STATUS "Target is cppTests")
else()
    message(STATUS "Target is not cppTests")
endif()


message(STATUS "Target is ${TARGET}")
set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(cppTests ${SOURCE_FILES})

Then I call the following:

/home/username/Software/clion-2017.1.1/bin/cmake/bin/cmake --build /home/username/Projects/cppTests/cmake-build-debug --target cppTests -- -j 8

How can I check target cppTests in CMake script after --target options ? I am looking for something like MAKECMDGOALS in Makefiles. I have found any useful solution ...

Answer

Craig Scott picture Craig Scott · May 16, 2017

The developer chooses which target(s) to build after CMake has generated the project files. When CMake is being run, CMake cannot know what target the developer will build. Therefore, what you are asking for doesn't really make sense for a CMake project. In a Makefile, there is no separate configure step, it is part of the build, which is how it can provide a feature like MAKECMDGOALS. It might also be worth reconsidering if you really want this functionality of Makefiles anyway, as it isn't meant for typical use (emphasis mine):

Make will set the special variable MAKECMDGOALS to the list of goals you specified on the command line. If no goals were given on the command line, this variable is empty. Note that this variable should be used only in special circumstances.

In your example, you are also misusing if(TARGET...). That construct is used to test whether a particular CMake target has been defined by the project (which in your example it doesn't until after the if() command, so it would always evaluate to false). See the docs here for details.