Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

c++ - Visual Studio: How to test (in code / static_assert) if a compiler option is enabled

I would like to check, in the code, if certain options where set at compile time.

Specifically, I have implemented some exception handling and would like to use a static_assert to be sure the /EHa option was set in the Visual Studio compiler. (I am using 2017 and 2019 with C++Latest enabled)

My solution has 54 projects each of which have 4 configs.... Easy to miss one. Or... I might want the code to be different if the option is not set....

many thanks

question from:https://stackoverflow.com/questions/65911232/visual-studio-how-to-test-in-code-static-assert-if-a-compiler-option-is-ena

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thanks gentlemen.

As I played with the options, I did find that the compiler is already giving a warning for this : warning C4535: calling _set_se_translator() requires /EHa

I looked to see if that was an attribute or decorator on the function in the VS headers so I could transplant it directly in my code, but could not find anything.

So far, I have thus settled on adding a comment in the code for other developers to see when the warning is given.

// Save & Restore the Structured Exception Handler
// Set our own handler during the call
class Scoped_SE_Translator
{
private:
    const _se_translator_function old_SE_translator;
public:
    Scoped_SE_Translator() = delete;
    Scoped_SE_Translator(_se_translator_function new_SE_translator) noexcept :  // NOTE: Compiler option /EHa is required  ("Enable C++ Exception" = "Yes with SEH Exceptions")
        old_SE_translator{_set_se_translator(new_SE_translator)} { }
    ~Scoped_SE_Translator() noexcept { _set_se_translator(old_SE_translator); }
};

I also set up project defaults in my existing solution.props file:

  <ItemDefinitionGroup>
    <ClCompile>
      <ExceptionHandling>Async</ExceptionHandling>
      <FloatingPointExceptions>true</FloatingPointExceptions>
      <TreatSpecificWarningsAsErrors>4535;%(TreatSpecificWarningsAsErrors)</TreatSpecificWarningsAsErrors>
    </ClCompile>
  </ItemDefinitionGroup>

However, that depends on developers adding a line in new vcxproj files:

<Import Project="$(SolutionDir)SolutionSettings.props" />

I am not sure if there is a more 'forceful' way to ensure new projects have the 'correct' defaults.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...