Mix build flags for several configurations in CMake - cmake

According to CMake documentation here, we can use the build type to specify our own build types, adding flags to our custom build depending on the CMAKE_BUILD_TYPE option.
For example, if CMAKE_BUILD_TYPE == Profile, CMake will use CMAKE_CXX_FLAGS_PROFILE for the build flags.
I would like to know if there is any way to "inherit" build flags from another build type. For example, I want a trace and debug build and a trace and release build. Is it possible to do something like CMAKE_BUILD_TYPE=Trace_Debug which adds CMAKE_CXX_FLAGS_DEBUG and CMAKE_CXX_FLAGS_TRACE to the build? I guess this can have some problems as it would allow the project to have contradictory build flags, but nothing prohibits to add -O1 and -O3 to our flags now, so that problem already exists.

There is no such thing in CMake like "inheriting" a build type.
Is it possible to do something like CMAKE_BUILD_TYPE=Trace_Debug which adds CMAKE_CXX_FLAGS_DEBUG and CMAKE_CXX_FLAGS_TRACE to the build?
Just define a (new) variable CMAKE_CXX_FLAGS_TRACE_DEBUG and set its value appropriately. When setting the value of the variable you may use values from other variables:
# Combine values of two variables into the single one.
set(CMAKE_CXX_FLAGS_TRACE_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${CMAKE_CXX_FLAGS_TRACE}")
It is up to you to remove conflicting flags from the resulted variable. CMake has no knowledge about conflicting flags, it just passes them to the compiler tool.

Related

add_custom_target that DEPENDS on all and another target [duplicate]

I have a custom target, and I want it to depend on the default target (the one that is built with make).
add_custom_target(foo ....)
add_dependency(foo default_target_name_goes_here)
What is the name of the default target?
I've tried ALL, ALL_BUILD, MyProjectsName, DEFAULT,...
Finding anything in the CMake documentation is always an unsuccessful adventure...
UPDATE: it seems CMake was designed in such a way that this is extremely hard to fix/implement: bugreport getting +1's since 2009. Who indeed would like to have a custom target that depends on, for example, the all target? Or in other words: who does ever write make && make test?...
The default build target does not exist as a CMake target at CMake configure time. It is only exists in the generated build system. Therefore it is not possible to have the default target depend on a custom target.
I think a possible solution depends strongly on the use case. E.g. if this is for executing a test after the system has been build you would use CTest instead of calling make directly.
To your CMakeLists.txt you would add:
add_test(NAME foo COMMAND ...)
and then use CTest for building and executing:
ctest --build-and-test ...
More generally speaking and not considering the question of why you would like to do it - I think the best thing would be to just name and rely on concrete target dependencies instead of just taking ALL targets - I just wanted to add two possibilities to do what you wanted to do.
One would be to determine/track the list of all targets used as discussed here. This would look e.g. for library targets like this (getting your own/private GlobalTargetList):
macro(add_library _target)
_add_library(${_target} ${ARGN})
set_property(GLOBAL APPEND PROPERTY GlobalTargetList ${_target})
endmacro()
and use it at the end of your main CMakeLists.txt with
get_property(_allTargets GLOBAL PROPERTY GlobalTargetList)
add_dependencies(foo ${_allTargets})
Edit: Global BUILDSYSTEM_TARGETS property was released with CMake 3.7
The second - less favorable - approach does require that the foo target is not part of the ALL build (otherwise you end-up in an endless loop):
add_custom_target(foo)
set_target_properties(foo PROPERTIES EXCLUDE_FROM_ALL 1)
add_custom_command(
TARGET foo
PRE_BUILD
COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target ALL_BUILD --config $<CONFIGURATION>
)

What does CMAKE_BUILD_TYPE affect, other than the compiler flag selection?

I know that if if we set -DCMAKE_BUILD_TYPE=Release (or Debug etc.), then the values of CMAKE_C_FLAGS_RELEASE and CMAKE_CXX_FLAGS_RELEASE will be appended to CMAKE_C_FLAGS and CMAKE_C_FLAGS respectively.
But is this the only effect of setting the build type? If not, what are the other effects?
Actually, build type affects on many things. Among them:
generator expressions:
Expression $<$<CONFIG:DEBUG>:XXX> will be expanded to XXX with CMAKE_BUILD_TYPE set to Debug and to nothing otherwise.
Because generator expressions can be used in a number of commands, setting build type affects all commands which uses expressions dependent on build type.
libraries added by target_link_libraries with debug keyword take an effect only in Debug build type.
Similar to optimized keyword.
(Implicitely, this uses generator expressions described above).
Some properies of IMPORTED libraries.
Properties like IMPORTED_LOCATION have config-specific variants, which are choosen dependent on configuration type.
Often IMPORTED libraries are created as a result of find_package() call, so your project may be linked with 3d-party project in configuration-dependent manner.
CONFIGURATION-specific part of install command.
Only those CONFIGURATION <conf> part are applies, which corresponds to active configuration.
Multi-configuration tools doesn't use CMAKE_BUILD_TYPE variable, but they still have a notion of the "build type". That build type is NOT known at configuration stage, when CMake parses CMakeLists.txt, it is set only when performing a build of the project. Nevertheless, this build type "retroactively" affects on all properties described above.
Also, with multi-configuration build tools selected build type is appended to the location of output artifacts, like executables and libraries (see e.g. description of RUNTIME_OUTPUT_DIRECTORY target's property).

Get build command or all compiler flags that will be used to build a target

Is there a sensible way to get a CMake variable containing the build command or all the compiler flags that CMake will associate with a target?
It doesn't seem practical to try to gather and maintain a list of all properties that could add flags. Besides, CMake must have this info somewhere, since it has to eventually generate a build system.
From the CMake docs it looks like this feature once existed and was provided by calling build_command() but this was replaced:
Note In CMake versions prior to 3.0 this command returned a command
line that directly invokes the native build tool for the current
generator.
Is there a new command that gives the old behavior of build_command()?
Is there a sensible way to get a CMake variable containing the build command or all the compiler flags that CMake will associate with a target?
The answer is no (CMake 3.23 is latest at time of writing), not during the CMake configure step.
In general, such a thing is ill-defined, which is likely why it was removed from CMake and will likely not be re-added. The complications arising from generator expressions, multi-config generators, generators that don't construct command lines (like VS/msbuild), source-file-specific properties, and the simple fact that after the command is called, relevant state might change, all make such efforts quixotic.
Honestly, this is such an odd thing to want at configure time, I wonder if this isn't an XY problem. It's unlikely that one target depends on another in such a way that the entire eventual command line is needed (rather than a particular property) to create it.
I know this is many years later now, but what were you trying to do?
CMake provides many ways post-generation to get information about the compiler command lines.
There's the CMake File API, meant for IDE integration,
The CMAKE_EXPORT_COMPILE_COMMANDS option that creates a Clang-compatible compile_commands.json, and then there's
The CMAKE_<LANG>_COMPILER_LAUNCHER variables that would let you instrument a full command line with a custom script while the build is running.
One of these might be useful. The latter is commonly used with ccache, but can be (ab)used with any arbitrary program as long as the output file is eventually generated.
Note that the latter two only work with the Makefile and Ninja generators.
If you want the final output of how the source files will actually be compiled you will want to look at the generated files. I don't really know a better way currently:
Example:
Here is an example output from Ninja Multi
build\CMakeFiles\impl-Release.ninja
This file will list all of the compile definitions, compiler flags, include directories, object directory, etc.
Under the path "cmake-build-debug/CMakeFiles/" you'll find a folder named as "TopFolderOfYourProject.dir", where the cmake generates all its build system files, including a file "build.make". In this file you can see something like this:
CMakeFiles/somepath/somesourcefile.c
#$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=xxx\cmake-build-debug\CMakeFiles --progress-num=$(CMAKE_PROGRESS_1) "Building C object CMakeFiles/somepath/somesourcefile.c.obj"
Besides this, you can find extra info about the flags in the file "flags.make", it contains all extra compiler flags specified by developers.
And in "includes_C.rsp/includes_CXX.rsp" you can see the including path.
Build flags are, actually, associated with source files, because you can have differrent flags for different files. On the other hand, for the most cases these flags are equivalent.
Anyways, to get all build flags for a source file you can use COMPILE_FLAGS property:
get_source_file_property(RESULT file.cpp COMPILE_FLAGS)

Use generator expression to set build type specific flags

I'd like to set some specific compile flags based on my current build configuration in cmake. I thought generator expressions would allow me to do this, but they don't appear to be working the way I expected.
I'm using the following command to set compile options to my main target. Both the expressions appear to always evaluate true as --debug and -Oh are passed to compiler no matter what CMAKE_BUILD_TYPE is set to.
target_compile_options(${PROJECT_NAME}
PUBLIC
${COMMON_COMPILER_FLAGS}
$<$<CONFIG:Debug>:--debug>
$<$<CONFIG:Release>:-Oh>
)
I'm using cmake 3.4.1 on Windows and I'm cross-compiling with the IAR toolchain. To be more specific, I'm executing cmake from the bash shell in Cygwin, but its still the Windows executable. I'm using the Unix Makefile generator.
It looks like the second flag is getting picked up from somewhere and just so happens to be ordered at the right spot to give me the above impression.
I can update with an explanation for that when I determine it, but the generator expressions appear to have always been working. I inserted some keyboard-smash in for both and it became apparent only one was getting through to command line.
EDIT:
The unwanted optimization flag was coming from target_compile_options calls on a couple libraries that are linked to my main target. I had the scope options set to PUBLIC, which means the options populate INTERFACE_COMPILE_OPTIONS. I changed the scopes to PRIVATE and it got rid of the unwanted flag.

CMake Fortran compiler-dependent flags

I'm using CMake for a moderate-sized Fortran project; sometimes I build it with gfortran, other times with ifort. When I want to do a debug build, the compiler flags are different; I'd like to have CMake automatically check which compiler is being used and set the flags accordingly.
It looks like this answer shows how to do the same thing for different C++ compilers. There's an example of how to check compilers with Fortran, using
if (Fortran_COMPILER_NAME MATCHES "gfortran.*")
However, this fails to invoke the conditional, because CMake has decided to use f95. Of course, f95 happens to alias to gfortran, but CMake doesn't detect that.
What's the right way to do this?
You can use also use CMAKE_Fortran_COMPILER_ID:
if ("${CMAKE_Fortran_COMPILER_ID}" MATCHES "Intel")
# something
elseif("${CMAKE_Fortran_COMPILER_ID}" MATCHES "GNU")
# something else
endif
Best way is to read file CMakeDetermineFortranCompiler.cmake and related files referenced from it.
Rather than trying to special case for different compilers you should actually test that your compiler supports the flags you want to set using check_fortran_compiler_flag like so:
include(CheckFortranCompilerFlag)
check_fortran_compiler_flag("-my-flag" _my_flag)
if(_my_flag)
set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -my-flag")
endif()
This is both safer and (I think) simpler because you don't need the implied knowledge of which compiler (and version) supports which flag.
It's simple. Only indicate the full path of compiler installed e.g.gfortran. the code: cmake -DCMAKE_fortran_PATH=/usr/bin/gfortran