1

In cmake, the default release compiler flags for gcc are -O2 -DNDEBUG. I want them to be -Ofast -NDEBUG. And I want that to be true for every project I do things with in cmake without imposing that choice on any other consumers of my project.

How do I do that?

I could edit them into that project's CMakeLists.txt file. But then I'm forcing other people to agree with my choice. Also, I have to be really careful about how I do it to make sure that I only affect compilers for which that is a valid set of flags to use.

I could use ccmake on every project every time I check out a new tree or create a new build environment. But that's a huge hassle when I want to set the flags to the same thing every time.

Is there a way to set it up so that for me, personally, the default compiler flags for clang and gcc for the various build types are what I want them to be?

Similarly, it's noticing I have ccache and gcc. And that's fine. But it might be nice to force a different default choice for compiler as well, but just for me personally, not for anybody else who chooses to use my project.

Is this possible?

Omnifarious
  • 54,333
  • 19
  • 131
  • 194

2 Answers2

0

My current answer to this question is to create a global ~/.config/Kitware/default.cmake file that contains initial cache settings and to use cmake -C <path to default.cmake> ... remainder of cmake options ... to run cmake.

In the process of figuring this out I initally named the file ~/.config/Kitware/CMakeCache.txt and found something quite odd that appears to be a bug in cmake. I posted this question about it: Why does this cmake initial cache file result in such strange errors?

Omnifarious
  • 54,333
  • 19
  • 131
  • 194
0

I normally set compiler flags in cmakelists.txt by adding an environment variable into my build script, then referencing that in cmakelists.txt.

#build.sh
export MY_CXXFLAGS="-std=gnu++11 -Ofast -NDEBUG -Wall -Wno-unused-function -Wno-unknown-pragmas"
cmake `pwd` -Dtest=ON
make -j9

Then in my CMakeLists.txt, I'll have the following line:

SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} $ENV{MY_CXXFLAGS}")

It's simple then to pass arguments to build.sh, which is just a bash script, to change the content of MY_CXXFLAGS, based on the users needs. (E.g. build.sh -b DEVELOP|DEBUG|RELEASE etc).

stack user
  • 835
  • 1
  • 9
  • 28
  • It's good as long as only optional (non-default) flags are expected. I would strongly suggest that all default parameters are handled outside of variables. It's very frustrating to start or resume a project and spend a half-day setting up environment variables or missing an environment variable and can't figure out why everything breaks. – Stewart Sep 26 '17 at 19:57
  • Environment variables can be set within the build script, as in the MY_CXXFLAGS variable given in the example code. So you don't have to spend a half-day setting anything up. Your point is orthogonal to the problem at hand. – stack user Dec 26 '20 at 08:33