cmakepcapplusplus

FetchContent_MakeAvailable adds optimization flag


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.


Solution

  • 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#L199

    if(NOT CMAKE_BUILD_TYPE)
      set(CMAKE_BUILD_TYPE
          "Release"
          CACHE STRING "Choose the type of build." FORCE)
      set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release")
    endif()
    

    Because of such setting, compiler options are taken not only from CMAKE_CXX_FLAGS variable, but also from CMAKE_CXX_FLAGS_RELEASE variable, which is usually set to -03 in a toolchain for gcc-like compilers.


    In the documentation CMake recommends to set CMAKE_BUILD_TYPE variable:

    The default value is often an empty string, but this is usually not desirable and one of the other standard build types is usually more appropriate.

    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.