c++visual-studiomfcvisual-studio-2022cpp-core-guidelines

How do I define __cpp_exceptions for gsl:narrow to compile?


I am getting confused again :(

I have looked at this discussion:

detect at compile time whether exceptions are disabled

I am new to trying to use GSL. I have copied the GSL folder to my PC and added a #include to my stdafx.h file.

But the gsl:narrow command is not exposed. I then see it refers to the __cpp_exceptions macro/token.

I tried to #define it in my pre-processor's list in the project settings and it does not like it.

How do I activate this __cpp_exceptions?

The gsl header file:

#ifndef GSL_GSL_H
#define GSL_GSL_H

#include <gsl/algorithm>   // copy
#include <gsl/assert>      // Ensures/Expects
#include <gsl/byte>        // byte
#include <gsl/pointers>    // owner, not_null
#include <gsl/span>        // span
#include <gsl/string_span> // zstring, string_span, zstring_builder...
#include <gsl/util>        // finally()/narrow_cast()...

#ifdef __cpp_exceptions
#include <gsl/narrow> // narrow()
#endif

#endif // GSL_GSL_H

I am trying to compile MFC C++ project with Visual Studio 2022 Preview.


Solution

  • Whether or not the __cpp_exceptions macro is pre-defined by the MSVC compiler depends on your Visual Studio project's settings (i.e. whether or not C++ Exceptions are enabled).

    You can check/change the relevant setting by right-clicking on the project in the Solution Explorer pane and selecting the "Properties" command.

    In the popup that appears, open the "C/C++" node in the navigation tree on the left and select the "Code Generation" sub-node. Then, in the right-hand pane, make sure that the "Enable C++ Exceptions" option is set to "Yes (/EHsc)" (other varieties of the "Yes" option may also work):

    enter image description here

    (Note: This works in Visual Studio 2019. I don't have V/S 2022 installed on my PC, so I can't check it in that version – but I would imagine the process is very similar.)

    The following short console-mode program demonstrates the difference caused by changing that setting:

    #include <iostream>
    int main()
    {
        #ifdef __cpp_exceptions
        std::cout << "yes";    // With "Yes (/EHsc)"
        #else
        std::cout << "no";     // With "No"
        #endif
        std::cout << std::endl;
        return 0;
    }