Search code examples
cmakeyaml-cpp

Is it possible to set `-fexceptions` flag for building yaml-cpp using CMake


I am trying to integrate libyaml-cpp to a project that uses CMake. I added the yaml-cpp using add_subdirectory(yaml-cpp), to the CMakefile. However my project uses the following flag -fno-exceptions for the gcc compiler settings. This flag issues the following error when building yaml-cpp :

/yaml-cpp/include/yaml-cpp/node/impl.h:60:35: error: exception handling disabled, use -fexceptions to enable throw InvalidNode(m_invalidKey);

So, the solution is to enable the -fexceptions flag. But I want to enable this only for the yaml-cpp build and not the rest of the project.

I am new to Cmake and yaml-cpp. Is there a way to set this flag -fexceptions in the Cmakefile (for yaml-cpp), so that build goes through.?


Solution

  • Assuming you are using the yaml-cpp code in the GitHub repository here, and assuming you are building on a Unix system, the compilation options (flags) for the yaml-cpp target are applied in the CMake file here, at the target_compile_options() call. Just add the -fexceptions flag to that call, for the not-msvc case:

    yaml-cpp/CMakeLists.txt:

    ...
    target_compile_options(yaml-cpp
      PRIVATE
        # Add -fexceptions to this line.
        $<${not-msvc}:-Wall -Wextra -Wshadow -Weffc++ -Wno-long-long -fexceptions>
        $<${not-msvc}:-pedantic -pedantic-errors>
    
        $<$<AND:${backport-msvc-runtime},${msvc-rt-mtd-static}>:-MTd>
        $<$<AND:${backport-msvc-runtime},${msvc-rt-mt-static}>:-MT>
        $<$<AND:${backport-msvc-runtime},${msvc-rt-mtd-dll}>:-MDd>
        $<$<AND:${backport-msvc-runtime},${msvc-rt-mt-dll}>:-MD>
    
        # /wd4127 = disable warning C4127 "conditional expression is constant"
        # http://msdn.microsoft.com/en-us/library/6t66728h.aspx
        # /wd4355 = disable warning C4355 "'this' : used in base member initializer list
        # http://msdn.microsoft.com/en-us/library/3c594ae3.aspx
        $<$<CXX_COMPILER_ID:MSVC>:/W3 /wd4127 /wd4355>)