In a GCC compiled project,
How do I run CMake for each target type (debug/release)?
How do I specify debug and release C/C++ flags using CMake?
How do I express that the main executable will be compiled with g++ and one nested library with gcc?
With CMake, it's generally recommended to do an "out of source" build. Create your CMakeLists.txt in the root of your project. Then from the root of your project:
mkdir Release
cd Release
cmake -DCMAKE_BUILD_TYPE=Release ..
make
And for Debug (again from the root of your project):
mkdir Debug
cd Debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
make
Release / Debug will add the appropriate flags for your compiler. There are also RelWithDebInfo and MinSizeRel build configurations.
You can modify/add to the flags by specifying a toolchain file in which you can add CMAKE_<LANG>_FLAGS_<CONFIG>_INIT variables, e.g.:
set(CMAKE_CXX_FLAGS_DEBUG_INIT "-Wall")
set(CMAKE_CXX_FLAGS_RELEASE_INIT "-Wall")
See CMAKE_BUILD_TYPE for more details.
As for your third question, I'm not sure what you are asking exactly. CMake should automatically detect and use the compiler appropriate for your different source files.
A lot of the answers here are out of date/bad. So I'm going to attempt to answer it better. Granted I'm answering this question in 2020, so it's expected things would change.
How do I run CMake for each target type (debug/release)?
First off Debug/Release are called configurations in cmake (nitpick).
If you are using a single configuration generator (Ninja/Unix-Makefiles) you must specify the CMAKE_BUILD_TYPE.
Like this:
# Configure the build
cmake -S . -B build/ -D CMAKE_BUILD_TYPE=Debug
# Actually build the binaries
cmake --build build/
# Configure a release build
cmake -S . -B build/ -D CMAKE_BUILD_TYPE=Release
# Build release binaries
cmake --build build/
For multi-configuration generators it's slightly different (Ninja Multi-Config, Visual Studio)
# Configure the build
cmake -S . -B build
# Build debug binaries
cmake --build build --config Debug
# Build release binaries
cmake --build build --config Release
If you are wondering why this is necessary it's because cmake isn't a build system. It's a meta-build system (IE a build system that build's build systems). This is basically the result of handling build systems that support multiple-configurations in 1 build. If you'd like a deeper understanding I'd suggest reading a bit about cmake in Craig Scott's book "Professional CMake: A Practical Guide
How do I specify debug and release C/C++ flags using CMake?
The modern practice is to use target's and properties.
Here is an example:
add_library(foobar)
# Add this compile definition for debug builds, this same logic works for
# target_compile_options, target_link_options, etc.
target_compile_definitions(foobar PRIVATE
$<$<CONFIG:Debug>:
FOOBAR_DEBUG=1
>
)
NOTE: How I'm using generator expressions to specify the configuration!
Using CMAKE_BUILD_TYPE will result in bad builds for any multi-configuration generator!
Further more sometimes you need to set things globally and not just for one target.
Use add_compile_definitions, add_compile_options, etc. Those functions support generator expressions. Don't use old style cmake unless you have to (that path is a land of nightmares)
How do I express that the main executable will be compiled with g++ and one nested library with gcc?
Your last question really doesn't make sense.
For debug/release flags, see the CMAKE_BUILD_TYPE variable (you pass it as cmake -DCMAKE_BUILD_TYPE=value). It takes values like Release, Debug, etc.
https://gitlab.kitware.com/cmake/community/wikis/doc/cmake/Useful-Variables#compilers-and-tools
cmake uses the extension to choose the compiler, so just name your files .c.
You can override this with various settings:
For example:
set_source_files_properties(yourfile.c LANGUAGE CXX)
Would compile .c files with g++. The link above also shows how to select a specific compiler for C/C++.
Instead of manipulating the CMAKE_CXX_FLAGS strings directly (which could be done more nicely using string(APPEND CMAKE_CXX_FLAGS_DEBUG " -g3") btw), you can use add_compile_options:
add_compile_options(
"-Wall" "-Wpedantic" "-Wextra" "-fexceptions"
"$<$<CONFIG:DEBUG>:-O0;-g3;-ggdb>"
)
This would add the specified warnings to all build types, but only the given debugging flags to the DEBUG build. Note that compile options are stored as a CMake list, which is just a string separating its elements by semicolons ;.
// CMakeLists.txt : release
set(CMAKE_CONFIGURATION_TYPES "Release" CACHE STRING "" FORCE)
// CMakeLists.txt : debug
set(CMAKE_CONFIGURATION_TYPES "Debug" CACHE STRING "" FORCE)
If you want to build a different configuration without regenerating if using you can also run cmake --build {$PWD} --config <cfg> For multi-configuration tools, choose <cfg> ex. Debug, Release, MinSizeRel, RelWithDebInfo
https://cmake.org/cmake/help/v2.8.11/cmake.html#opt%3a--builddir
Related
I'm using CLion with MinGW-GCC on the Windows-x64 platform - This is the background of the problem.
I was trying to install gtest before. But a lot of confusion arose in the middle.
First time I ran those commands(in googletest-release-1.12.1\) according to the instructions of googletest-release-1.12.1\googletest\README.md:
mkdir build
cd build
cmake ..
But I got error messages like:
CMake Error at CMakeLists.txt:51 (project):
Failed to run MSBuild command:
C:/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe
to get the value of VCTargetsPath:
Then I changed my last command to
cmake -G "MinGW Makefiles" ..
because I use make provided by MinGW. I don't know whether it's right but, it ran properly.
then I called
make
make install
make ran smoothly. But when I ran make install, I got these messages:
Install the project...
-- Install configuration: ""
-- Installing: C:/Program Files (x86)/googletest-distribution/include
CMake Error at googlemock/cmake_install.cmake:41 (file):
file INSTALL cannot make directory "C:/Program Files
(x86)/googletest-distribution/include": No such file or directory.
Call Stack (most recent call first):
cmake_install.cmake:42 (include)
make: *** [Makefile:109: install] Error 1
I have no idea at all this time. So I changed my way. According to this answer, I copied the whole library into my project and edited CMakeLists.txt like this:
cmake_minimum_required(VERSION 3.23)
project(gtest_study)
set(CMAKE_CXX_STANDARD 20)
add_subdirectory(googletest-release-1.12.1)
include_directories(googletest-release-1.12.1/googletest/include)
include_directories(googletest-release-1.12.1/googlemock/include)
add_executable(gtest_study main.cpp)
target_link_libraries(gtest_study gtest gtest_main)
target_link_libraries(gtest_study gmock gmock_main)
So my questions are:
Is there any difference between the two which build it using make and cmake metioned firstly, and just use commands like include_directories and target_link_libraries in CMakeLists.txt? (maybe like .h and .dll file? Or just completely the same? I don't know)
When I use make install to install a library on Windows, what should I do in particular? Specify some directory (I don't know which one) or what?
Although in my system environment I use MinGW-makefile, in CLion which the libraries are eventually used, I use ninja as the generator for CMake (it just comes with CLion, not installed for the system). Do I have to specify it and how? (-G "Ninja"doesn't work in my native env)
The difference between
cmake ..
and
cmake -G "MinGW Makefiles" ..
Is the choice of generator: The former uses the default generator, the latter uses the generator you specified. (cmake --help should put a * next to the default generator.)
Based on the error message I assume this is a visual studio generator and you may not be able to run that one properly from within a MinGW terminal.
In the latter case the default install directory seems to be based on the target OS (Windows) but does not seem to incorporate the fact that you're running from a MinGW terminal where the default install path (C:/Program Files (x86)/googletest-distribution) is not valid.
You could try to fix this by providing it during cmake configuration (passing -D 'CMAKE_INSTALL_PREFIX=/c/Program Files (x86)/googletest-distribution' before the source dir) or by providing the install directory during the installation.
The following process should allow you to install the lib. I'm using my preferred way of building here, i.e. not using build system dependent commands, but using cmake to run the build/install commands. I assume the working directory to be the root directory of the gtest sources:
cmake -G "MinGW Makefiles" -S . -B build
cmake --build build
cmake --install build --prefix '/c/Program Files (x86)/googletest-distribution'
The last command needs to be run with admin privileges, the first 2 I don't recommend running as admin. You could instead install to a directory where you do have the permissions to create directories even without admin privileges.
The difference between using the process described above and using add_subdirectory is that the former results in a installation on the system which can be used via find_package and the google test libs won't be rebuilt for every project where you do this.
...
project(gtest_study)
...
# you may need to pass the install location via -D CMAKE_PREFIX_PATH=<install_location> during configuration for this to work
find_package(GTest REQUIRED)
target_link_libraries(gtest_study PRIVATE GTest::gtest_main GTest::gmock)
The latter builds the google test project as part of your own project build and for every project where you use this approach a seperate version of the google test libs is built. Note: there should be no need to specify the include dirs yourself, since this kind of information is attached to the cmake target and gets applied to the linking target automatically:
#include_directories(googletest-release-1.12.1/googletest/include)
#include_directories(googletest-release-1.12.1/googlemock/include)
add_executable(gtest_study main.cpp)
target_link_libraries(gtest_study PRIVATE gtest_main gmock)
As for 3.: The CMake generator used for building GTest should be independent of the generator of the project using it. The thing that's important is that the compilers used by the build systems are compatible. I cannot go into detail about this, since I've never used CLion and therefore have too little knowlege about the compilers used by it. (Personally I'm working with Visual Studio on Windows.)
I want to build my C++ applications from the Windows PowerShell command line using CMake and MinGW.
When I do this in the "normal way," with these commands:
mkdir build
cd build
cmake ..
make
CMake chooses Visual Studio as the default compiler, and doesn't generate any Makefiles for me.
I want CMake to use MinGW as the default compiler, and generate Makefiles.
It works exactly the way that I want it to when I run these commands, adding the -G "MinGW Makefiles" flag:
mkdir build
cd build
cmake .. -G "MinGW Makefiles"
make
How can I make CMake behave this way all the time, without adding the -G "MinGW Makefiles" flag?
I've tried setting up a CMAKE_GENERATOR environment variable in Windows, and pointing it to "path\to\mingw\bin", "path\to\mingw\bin\mingw32-make.exe", as well as a string that reads "MinGW Makefile".
None of these worked for me after running refreshenv and then trying to run cmake .. again.
Does anybody know if this is the correct environment variable to use in order to specify CMake's default behavior? If it is, what value should I be using?
How can I make CMake behave this way all the time, without adding the -G "MinGW Makefiles" flag?
You can't, not in any version of CMake released to date. CMake chooses a generator before it starts evaluating any CMakeLists.txt files. By default, it chooses a generator based on runtime platform and available toolsets, and command-line options are the only way presently available to influence or override CMake's choice of generator.
In comments, #Tsyvarev pointed out an open CMake issue report asking for the very same feature you are asking for. The associated comment thread provides more detail, and the last comment was earlier this year. I would guess that eventually CMake will add support for specifying a generator via environment variable, but for now, your -G option is the only available alternative. You could consider scripting it if you want to save keystrokes and reduce the risk of typos.
I know this is late. but in case someone came here and find this answer useful
all you have to do is to create a function something like this:
function gcmake {cmake .. -G "MinGW Makefiles"}
then you can simply type
mkdir build
cd build
gcmake ..
make
tip: you can add this function to your profile so that it will be saved to any new session. you can follow this nice guide
cmake uses Visual Studio generator for MinGW on Windows by default (even without Visual Studio!), this is the real annoying issue (Cygwin is not affected).
We need to work around MinGW only. What will be the most reliable hook for MinGW? I think MSYSTEM is very popular environment variable that will always be defined for MinGW.
You can place PreLoad.cmake in the project root with the following content:
if (NOT "$ENV{MSYSTEM}" STREQUAL "" AND "$ENV{VisualStudioVersion}" STREQUAL "")
find_program (CMAKE_NINJA_BINARY NAMES "ninja")
if (CMAKE_NINJA_BINARY)
set (
CMAKE_GENERATOR "Ninja"
CACHE INTERNAL "Cmake generator"
)
return ()
endif ()
find_program (CMAKE_MAKE_BINARY NAMES "gmake" "make")
if (CMAKE_MAKE_BINARY)
set (
CMAKE_GENERATOR "Unix Makefiles"
CACHE INTERNAL "Cmake generator"
)
return ()
endif ()
endif ()
Unfortunately this solution is not universal:
MSYSTEM=MINGW64 cmake -G "Unix Makefiles" ..
CMake Error: Error: generator : Unix Makefiles
Does not match the generator used previously: Ninja
Either remove the CMakeCache.txt file and CMakeFiles directory or choose a different binary directory.
If you are setting CMAKE_GENERATOR inside PreLoad.cmake than you are loosing ability to use -G cmake option. If you don't need this option, than this solution will be just fine.
PS It is not possible to access -G option value inside PreLoad.cmake as CMAKE_GENERATOR or another option. So it is not possible to add guard case like NOT DEFINED CMAKE_GENERATOR to check whether generator has been provided explicitly using -G option.
In this answer, it says Debug is the default cmake build configuration.
But I have a different observation:
I have following in my CMakeLists.txt to choose debug and release versions of a lib according to the current build configuration.
target_link_libraries(MyApp debug Widgets_d)
target_link_libraries(MyApp optimized Widgets)
It seems that when I invoke cmake without sepcifying -DCMAKE_BUILD_TYPE flag, Widgets is used instead of Widgets_d (When I delete Widgets and try to build, make complains that lib is not there). So that means by default the build configuration is optimized, not debug.
So what actually is the default build configuration? If it is debug, what could be wrong with my CMakelists.txt?
target_link_libraries with optimized keyword corresponds to all configurations, which are not debug.
Try adding message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") to your CMakeLists.txt to see the actual build type (I suppose it should be empty).
If depends on whether you are using a single-configuration generator (Makefiles) or a multi-configuration generator (Visual Studio, XCode).
The link cited in the question is about a multi-configuration generator. When using a multi-configuration generator, the configuration variable CMAKE_BUILD_TYPE is ignored. To select the configuration to build, cmake allows the switch --config, and this defaults to Debug. So
cmake --build .
in a multi-configuration project builds a Debug version.
However, when using a single-configuration generator, the switch --config is ignored. Only the configuration variable CMAKE_BUILD_TYPE is used to determine the build type, and this defaults to Release.
More background info on single- and multiconfiguration-generators in this answer.
My problem is as such :
I'm developing a small parser using Visual Studio 2010.
I use CMake as a build configuration tool.
But I find the default executable building behaviour, inconvenient.
What I want is, have my final program be located in :
E:/parsec/bin/<exe-name>.<build-type>.exe
rather than
E:/parsec/bin/<build-type>/<exe-name>.exe
How would you do that using CMake ?
There are several options:
Copy the executable after building
Customizing the output-directory for your executable(s)
Copy the executable after building
After a succesful build you can copy the executable (see Beginners answer), but perhaps it is nicer to use an install target:
Use the install command to specify targets (executables, libraries, headers, etc.) which will be copied to the CMAKE_INSTALL_PREFIX directory. You can specify the CMAKE_INSTALL_PREFIX on the commandline of cmake (or in the cmake GUI).
Customizing the output-directory for your executable(s)
Warning: It is not advised to set absolute paths directly in your cmakelists.txt.
Use set_target_properties to customize the RUNTIME_OUTPUT_DIRECTORY
set_target_properties( yourexe PROPERTIES RUNTIME_OUTPUT_DIRECTORY E:/parsec/bin/ )
As an alternative, modifying the CMAKE_RUNTIME_OUTPUT_DIRECTORY allows you to specify this for all targets in the cmake project. Take care that you modify the CMAKE_LIBRARY_OUTPUT_DIRECTORY as well when you build dlls.
set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin )
set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib )
Additional info: Take a look at these questions:
In CMake, how do I work around the Debug and Release directories Visual Studio 2010 tries to add?
CMake : Changing name of Visual Studio and Xcode exectuables depending on configuration in a project generated by CMake
How to not add Release or Debug to output path?
Most probably you will need to copy your binaries with a separate custom command which would look similar to this one:
add_custom_command(target your_target_name
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy ${EXAMPLE_BIN_NAME} ${PROJECT_BINARY_DIR}/.
)
Ok im using CMake to build C++ under Linux, for an ARM target. I have a #DEFINE in one of my .h files called DEBUG. If set, I would like for various methods for tracing over serial will be added into the build. I would like to be able to do this by doing e.g. "make debug" to build with this #DEFINE set, and have normal "make" build without setting it. Is this possible?
Also, it it possible to be able to specify a target to CMake? As I have 2 CMakeLists.txt right now, one for x86, and one for Armel (with different options such as to build with debug information on x86, compared to the ARM, which wants a stripped, size-optimised binary).
It seems you have two questions. One about debug, you can use CMAKE_BUILD_TYPE to separate your debug/release setting, and use $ cmake --build . --config Release or $ cmake --build . --config Debug to compile.
For the second, about cross build, it's possible. You can do like these:
According to this guide write configure files for arm and x86 respectively to set compiler, archiver, etc.. Suppose name the one of x86 as *config_x86.cmake* and *config_arm.cmake* for arm.
Define a cmake macro, such as *MY_TARGET*. And add the following code before the project command,
if (${MY_TARGET} STREQUAL "x86")
include(config_x86.cmake REQUIRED)
elseif (${MY_TARGET} STREQUAL "arm")
include(config_arm.cmake REQUIRED)
endif ()
Then generate your project files like this
$ cmake -DMY_TARGET=x86 "your code dir"
Debug and release builds are supported out of the box by CMake.
Say the top level CMakeLists.txt for your project is in ~/project/foobar, you can create separate debug and a release builds by doing this:
mkdir ~/project/build
mkdir ~/project/build/foobar-debug
cd ~/project/build/foobar-debug
cmake -DCMAKE_BUILD_TYPE:STRING=Debug ~/project/foobar
mkdir ~/project/build/foobar-rel
cd ~/project/build/foobar-rel
cmake -DCMAKE_BUILD_TYPE:STRING=Release ~/project/foobar
What's even better is that CMake supports not just the standard debug/release targets you're probably used to, but it supports minimum sized release, as well as release with debug info. See the other options for CMAKE_BUILD_TYPE at:
http://cmake.org/Wiki/CMake_Useful_Variables
Regarding definitions, you can do what you want like this in your CMakeLists.txt files:
if( CMAKE_BUILD_TYPE MATCHES "[Dd][Ee][Bb][Uu][Gg]" )
message( "INFO: DEBUG BUILD" )
# for debug type builds, turn on verbose makefiles
SET(CMAKE_VERBOSE_MAKEFILE ON)
# Tell other CMake files that we're doing a debug build
SET( DEBUG_BUILD 1 )
# Tell C/C++ that we're doing a debug build
ADD_DEFINITIONS( -DDEBUG )
endif()
if( CMAKE_BUILD_TYPE MATCHES "[Rr][Ee][Ll][Ee][Aa][Ss][Ee]" )
message( "INFO: RELEASE BUILD" )
endif()
CMake does not like supporting two targets, in other words two toolchains, in the same build tree. There's really no need for this anyway. Definitely use out-of-tree builds with one build tree for each of your possible targets. Something like this:
cd /path/to/x86_build
cmake /path/to/src/x86/CMakeLists.txt
cd /path/to/Armel_build
cmake /path/to/src/Armel/CMakeLists.txt