In the project I'm building I experience wrong behavior regarding optimization flags. Normally I build with -g -O0.
Recently I wanted to add the PcapPlusPlus library to my project so I added following lines to the CmakeLists.txt:
FetchContent_Declare(
pcapplusplus
GIT_REPOSITORY https://github.com/seladb/PcapPlusPlus.git
GIT_TAG v23.09)
FetchContent_MakeAvailable(pcapplusplus)
After adding this, my files compile with following flags -g -O3 -O3. I have no idea why -O3 is added only because above lines. If remove only one line, FetchContent_MakeAvailable(pcapplusplus), the additional flag -O3 is not added. Why it works that way, even when I set these flags globally at the beginning of my CmakeLists.txt hierarchy.
It looks like CMAKE_BUILD_TYPE variable is specified neither in your project nor in the commmand line when you run
cmake. But the project you include via FetchContent sets that variable to "Release": https://github.com/seladb/PcapPlusPlus/blob/v23.09/CMakeLists.txt#L199Because of such setting, compiler options are taken not only from
CMAKE_CXX_FLAGSvariable, but also from CMAKE_CXX_FLAGS_RELEASE variable, which is usually set to-03in a toolchain for gcc-like compilers.In the documentation CMake recommends to set CMAKE_BUILD_TYPE variable:
Note, that the setting of a default configuration in the given project is not very good one. E.g. in the case of multi-configuration generators (like Visual Studio) the variable CMAKE_BUILD_TYPE is not used, and setting it may confuse some CMake projects. For proper ways see that question.