if condition in .CMake files - cmake

I have the following variable in a .cmake file:
add_definitions(-DENABLE_TEST)
if(DEFINED ENABLE_TEST)
message("ENABLE_TEST defined")
else()
message("ENABLE_TEST NOT defined")
endif()
I have to use the variable in other CMakelists.txt too.
Why does the above "if" always coming out as not defined?
How do I check if the variable is defined or not?

The add_definitions() command adds compile definitions to the compilation of your source files. It does not define CMake variables. The if(DEFINED ... syntax checks for the existence of CMake or environment variables, not the existence of compile definitions.
You can use the set() CMake command to define CMake variables, then subsequently, check for their existence in this manner:
set(ENABLE_TEST 1)
if(DEFINED ENABLE_TEST)
message("ENABLE_TEST defined")
else()
message("ENABLE_TEST NOT defined")
endif()

Related

Get CMake to not be silent about sources it doesn't understand?

Suppose you have a very simple CMakeLists.txt
add_executable(silent T.cpp A.asm)
CMake will happily generate a C++ target for building silent, with T.cpp in it, but will silently drop any and all reference to A.asm, because it doesn't know what to do with the suffix.
Is there any way to get CMake to loudly complain about this source file it doesn't understand (to aid in porting a Makefile to CMake).
Ignoring unknown file extensions is - unfortunately for your case - by design.
If I look at the code of cmGeneratorTarget::ComputeKindedSources() anything unknown ends up to be classified as SourceKindExtra (to be added as such to generated IDE files).
So I tested a little and came up with the following script that evaluates your executable target source files for valid file extensions by overwriting add_executable() itself:
cmake_minimum_required(VERSION 3.3)
project(silent CXX)
file(WRITE T.cpp "int main() { return 0; }")
file(WRITE T.h "")
file(WRITE A.asm "")
function(add_executable _target)
_add_executable(${_target} ${ARGN})
get_property(_langs GLOBAL PROPERTY ENABLED_LANGUAGES)
foreach(_lang IN LISTS _langs)
list(APPEND _ignore "${CMAKE_${_lang}_IGNORE_EXTENSIONS}")
endforeach()
get_target_property(_srcs ${_target} SOURCES)
foreach(_src IN LISTS _srcs)
get_source_file_property(_lang "${_src}" LANGUAGE)
get_filename_component(_ext "${_src}" EXT)
string(SUBSTRING "${_ext}" 1 -1 _ext) # remove leading dot
if (NOT _lang AND NOT _ext IN_LIST _ignore)
message(FATAL_ERROR "Target ${_target}: Unknown source file type '${_src}'")
endif()
endforeach()
endfunction()
add_executable(silent T.cpp T.h A.asm)
Since you wanted a rather loudly complain by CMake I declared it an FATAL_ERROR in this example implementation.
CMake doesn't just drop unknown files in add_executable().
If alongside with
add_executable(silent T.cpp A.asm)
you have
add_custom_command(OUTPUT A.asm COMMAND <...>
DEPENDS <dependees>)
then whenever <dependees> changed CMake will rerun command for create A.asm before compiling the executable.
Note, that automatical headers scanning doesn't provide such functionality: if your executable includes foo.h then executable will be rebuilt only when foo.h itself is changed. Any custom command creating this header will be ignored.
However, you may change behavior of add_executable by redefining it. See #Florian's answer for example of such redefinition.

Difference between add_compile_options and SET(CMAKE_CXX_FLAGS...)

This question is related to Instruct Cmake to use CXX and CXXFLAGS when driving link? In the former question, we are trying to instruct CMake to use CXXFLAGS when it invokes the linker.
add_compile_options
We found that the following code
if (CMAKE_VERSION VERSION_LESS 2.8.12)
add_definitions(-foo)
else()
add_compile_options(-foo)
endif()
message(STATUS, "CXXFLAGS: ${CMAKE_CXX_FLAGS}")
produces the output
CXXFLAGS:
SET CMAKE_CXX_FLAGS
We found that the following code
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -foo" )
message(STATUS, "CXXFLAGS: ${CMAKE_CXX_FLAGS}")
produces the output
CXXFLAGS: -foo
Questions
We found CMake would create object files using -foo in both cases. So -foo is definitely making its way into CXXFLAGS.
What is the difference between the first set of CMake code and the second set of CMake code?
Why is CMAKE_CXX_FLAGS unset in one instance, and set in the other instance?
CMAKE_CXX_FLAGS is used to add flags for all C++ targets. That's handy to pass general arguments like warning levels or to selected required C++ standards. It has no effect on C or Fortran targets and the user might pass additional flags.
add_compile_options adds the options to all targets within the directory and its sub-directories. This is handy if you have a library in a directory and you want to add options to all the targets related to the library, but unrelated to all other targets. Additionally, add_compile_options can handle arguments with generator expressions. The documentation explicitly states, that
This command can be used to add any options, but alternative commands
exist to add preprocessor definitions (target_compile_definitions()
and add_definitions()) or include directories
(target_include_directories() and include_directories()).
add_definitions is intended to pass pre-processor values of the type -DFOO -DBAR=32 (/D on Windows) which defines and sets pre-processor variables. You could pass any flag, but the flags of the above form are detected and added to [COMPILE_DEFINITIONS][2] property, which you can later read and change. Here, you can use generator expressions, too. The documentation mentions scopes for directories, targets and source files.
For a given target, CMake will collect all flags from CMAKE_CXX_FLAGS, the target's and directory's COMPILE_DEFINITIONS and from all add_compile_options which affect the target.
CMAKE_CXX_FLAGS are not altered by the other commands or vice versa. This would violate the scope of these commands.

cmake: how to check if preprocessor is defined

I can't get cmake to test if a preprocessor has been defined or not. Eg:
cmake_minimum_required(VERSION 2.8.9)
project (cmake-test)
add_definitions(-DOS=LINUX)
if(NOT <what condition goes here?>)
message(FATAL_ERROR "OS is not defined")
endif()
The following tests don't work:
if (NOT COMMAND OS)
if (NOT DEFINED OS)
if (NOT OS)
I can get it to work by using set() and just testing for a regular cmake variable and then defining the preprocessor macro. Eg:
set(OS LINUX)
if (OS)
add_definitions(-DOS=${OS})
else()
message(FATAL_ERROR "OS is not defined")
endif()
In case, you're wondering why I need to test it if the variable/preprocessor is in the same file, it's because in the final implementation these will come from an external file which is includeed in the main CMakeFile.txt Eg:
include(project_defs.txt)
if (OS)
....
This is to complete the answer by arrowd.
I also tried the COMPILE_DEFINITIONS option as mentioned above by arrowd unsuccessfully.
Following the documentation of CMake, at least for version 3.x, it turns out that when you call add_definitions() in CMake, it adds the definitions to the COMPILE_DEFINITIONS directory property.
Therefore, lets say you are defining the following as per your code:
add_definitions(-DOS=LINUX)
To retrieve the string with the definitions added into the variable "MYDEFS" you can use the following lines in CMake:
get_directory_property(MYDEFS COMPILE_DEFINITIONS)
MESSAGE( STATUS "Compile defs contain: " ${MYDEFS} )
Then you can check if in ${MYDEFS} the define you are looking for exists or not. For instance
if(MYDEFS MATCHES "^OS=" OR MYDEFS MATCHES ";OS=")
MESSAGE( STATUS "OS defined" )
else()
# You can define your OS here if desired
endif()
Normally, all definitions that are passed to the compiler are controlled by CMake. That is, you create a CMake variable with
option(SOMEFEATURE "Feature description" ON)
or
set(OS "" CACHE STRING "Select your OS")
User sets them via cmake -D OS=DOS or in the CMake GUI. Then you can use if() operator to conditionally add_definitions() to the compiler command line.
UPDATE:
If you really want to access preprocessor flags, there is a COMPILE_DEFINITIONS target property. You can access it this way:
get_target_property(OUTVAR target COMPILE_DEFINITIONS)

Using constant folder with cmake

I have a constant MYPROJECT in my ~/.bashrc file:
export MYPROJECT = /home/loom/my_project
I can see the constant is defined in the terminal:
loom#loom$ ls -ld $MYPROJECT
drwxr-xr-x 25 loom loom 4096 Jul 21 22:12 /home/loom/my_project
I tried to use the constant in my CMakeLists.txt:
add_executable(booo src/main.cpp ${MYPROJECT}/foo/trunk/bar/File.h)
However, it produces an error:
CMake Error at CMakeLists.txt:17 (add_executable):
Cannot find source file:
/foo/trunk/bar/File.h
Tried extensions .c .C .c++ .cc .cpp .cxx .m .M .mm .h .hh .h++ .hm .hpp
.hxx .in .txx
CMake Error: CMake can not determine linker language for target: booo
CMake Error: Cannot determine link language for target "booo".
It is processed without errors if I have used explicit path without $MYPROJECT:
add_executable(booo src/main.cpp /home/loom/my_project/foo/trunk/bar/File.h)
How to use path defined in .bashrc in cmake?
Instead of
add_executable(booo src/main.cpp ${MYPROJECT}/foo/trunk/bar/File.h)
use
add_executable(booo src/main.cpp $ENV{MYPROJECT}/foo/trunk/bar/File.h)
The CMake documentation states:
Use the syntax $ENV{VAR} to read environment variable VAR. See also
the set() command to set ENV{VAR}.
https://cmake.org/cmake/help/v3.4/variable/ENV.html
Turning my comment into an answer
There are a lot of ways you could do this in CMake. Out of bad experiences with using environment variables directly inside CMake projects (they have to be valid not only during the first call to CMake configuration/generation but also later during all consecutive builds), I would recommend to transfer your constant into a cached CMake variable.
I'm using one of the following ways in my projects:
Injecting MYPROJECT CMake via its -D option, e.g.
cmake -DMYPROJECT:PATH=$MYPROJECT ..
Then CMake would cache this value in its own MYPROJECT internal variable.
When you get values from the "outside" you should think about what to do if no value is provided or it's not a valid directory. Throwing a fatal error and/or retry with a default value?
The following example shows only transformation steps and sanity checks (no default value retry):
if (NOT DEFINED MYPROJECT OR NOT IS_DIRECTORY MYPROJECT)
file(TO_CMAKE_PATH "$ENV{MYPROJECT}" _ENV_MYPROJECT_REL)
get_filename_component(_ENV_MYPROJECT "${_ENV_MYPROJECT_REL}" ABSOLUTE)
if (NOT _ENV_MYPROJECT)
message(FATAL_ERROR "Environment variable MYPROJECT not provided.")
else()
set(MYPROJECT "${_ENV_MYPROJECT}" CACHE INTERNAL "")
endif()
endif()
Using find_path(), which will also cache its result:
find_path(
MYPROJECT_INCLUDE_DIR
NAMES File.h
PATHS ENV MYPROJECT
/home/loom/my_project
PATH_SUFFIXES foo/trunk/bar
)
if (NOT MYPROJECT_INCLUDE_DIR)
...
Or - assuming your external project does not only consists of header files but also libraries like foo.a - following CMake's A Sample Find Module and extending the find_path() code from above by:
find_library(
MYPROJECT_LIBRARY
NAMES foo
PATHS ENV MYPROJECT
PATH_SUFFIXES foo/lib
)
if(MYPROJECT_INCLUDE_DIR AND MYPROJECT_LIBRARY AND NOT TARGET MyProject::MyProject)
add_library(MyProject::MyProject UNKNOWN IMPORTED)
set_target_properties(
MyProject::MyProject
PROPERTIES
IMPORTED_LOCATION "${MYPROJECT_LIBRARY}"
INTERFACE_INCLUDE_DIRECTORIES "${MYPROJECT_INCLUDE_DIR}"
)
endif()
Now you can use it directly as any other CMake target with
add_executable(booo src/main.cpp)
target_link_libraries(booo MyProject::MyProject)
More References
What's the CMake syntax to set and use variables?
preferred cmake project structure

Check CMake Cache Variable in Toolchain File

I'm having trouble setting a configuration variable via the command line. I can't determine it from the system, so I expect the user to specify:
cmake -DCMAKE_TOOLCHAIN_FILE=../android.toolchain -DANDROID_ABI:STRING="arm64" ..
Inside my android.toolchain, I have the following:
message(STATUS "Android ABI: ${ANDROID_ABI}")
if( "${ANDROID_ABI}" STREQUAL "" )
message(FATAL_ERROR "Please specifiy ABI at cmake call -DANDROID_ABI:STRING=armeabi or -DANDROID_ABI:STRING=arm64")
endif()
No matter what, it fails at this line EVEN THOUGH it prints out the correct arm64:
-- Android ABI: arm64
CMake Error at yaml-cpp/android.toolchain:45 (message):
Please specifiy ABI at cmake call -DANDROID_ABI:STRING=armeabi or -DANDROID_ABI:STRING=arm64
Could anyone direct me to what I'm doing wrong?
I think this has to do with:
-D adds a cache variable instead of a normal variable
This is in a toolchain file... it seems to ignore cache variables
Any thoughts or suggestions?
I don't pretend to fully understand what's going on behind the scenes, but here's a workaround that works for me:
# Problem: CMake runs toolchain files multiple times, but can't read cache variables on some runs.
# Workaround: On first run (in which cache variables are always accessible), set an intermediary environment variable.
if (FOO)
# Environment variables are always preserved.
set(ENV{_FOO} "${FOO}")
else ()
set(FOO "$ENV{_FOO}")
endif ()
CMake 3.6 introduces variable CMAKE_TRY_COMPILE_PLATFORM_VARIABLES which contains a list of variables, automatically passed from the main project to the project, created with try_compile.
A toolchain may add its variables to that list, so they could be extracted in a subproject:
message(STATUS "Android ABI: ${ANDROID_ABI}")
if( "${ANDROID_ABI}" STREQUAL "" )
message(FATAL_ERROR "Please specifiy ABI at cmake call -DANDROID_ABI:STRING=armeabi or -DANDROID_ABI:STRING=arm64")
endif()
# propagate the variable into "inner" subprojects.
list(APPEND CMAKE_TRY_COMPILE_PLATFORM_VARIABLES "ANDROID_ABI")
Caveats:
This approach affects only to source flow of try_compile command. It won't work when try_compile is used for create fully-fledged CMake project with signature
try_compile(<resultVar> <bindir> <srcdir> <projectName> ...)
(Approach with setting environment variable, as described in the #sorbet answer, works perfectly in this case.)
This approach won't work for a subproject, created with ExternalProject_Add.
(Approach with setting environment variable fails in that case too.)