Search code examples
visual-studiovisual-c++buildbuild-process

How can I make the Microsoft C++ compiler treat unknown flags as errors rather than warnings?


For various reasons, I would like to be able to script the detection of whether the MS C++ compiler honors a particular flag. I'm using the compiler from the Windows 7.1 SDK:

C:\> cl /version
Microsoft (R) C/C++ Optimizing Compiler Version 16.00.30319.01 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

So lets say I want to know if the flag /GLEFGB is supported by this compiler (which it is not, because it doesn't exist):

C:\>cl /c ./foo.cc /GLEFBG
Microsoft (R) C/C++ Optimizing Compiler Version 16.00.30319.01 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

cl : Command line warning D9002 : ignoring unknown option '/GEFBG'
foo.cc

OK, good start, but it is a warning, and it doesn't set the exit status to invalid:

C:\>echo %errorLevel%
0

So we should be done if we turn on warnings as errors with /WX, right?

C:\>cl /c ./foo.cc /WX /GLEFBG

Microsoft (R) C/C++ Optimizing Compiler Version 16.00.30319.01 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

cl : Command line warning D9002 : ignoring unknown option '/GEFBG'
foo.cc

Wrong. This is getting disappointing. Maybe D9002 isn't captured by /WX for some reason? Maybe we can explicitly make it an error by using /we with that code? Care to guess whether this will work?

C:\>cl /c ./foo.cc /WX /weD9002 /GLEFBG
Microsoft (R) C/C++ Optimizing Compiler Version 16.00.30319.01 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

cl : Command line error D8021 : invalid numeric argument '/weD9002'

Nope, now we error out because apparently the tag for this compiler warning is not a legal argument to /we. I also tried /we9002, which doesn't work either.

So, now I am out of ideas. Any thoughts on how to convince cl to error out with a non-zero exit status if passed an invalid flag? It is really hard to interrogate the compiler for flag support without this sort of behavior.


Solution

  • Following @HansPassant bug report, the following flag was added in: Visual Studio 2022 version 17.0 preview 4.

    /options:strict unrecognized compiler options are an error
    
    > cl /options:strict /empanadas test.c
    Microsoft (R) C/C++ Optimizing Compiler Version 19.40.33808 for x64
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    cl : Command line error D8043 : unknown option '/empanadas'