Visual Studio Compiler Default for /O - c++

Does VS2010/12's compiler use a default optimization level when none of /Od,/O1,/O2,/Ox is provided in a C++ compilation command line?
I'm currently using /Od since I witnessed some optimization related bugs when using the other levels. However, this leads to /GS being disabled - which is unwanted.
When I clear the box for the "Project Properties->C/C++->Optimization->Optimization" option, I see the command line indeed doesn't contain any option. But I don't know if this just means the compiler uses some default optimization level.

No optimization seems to be the default - see output from "cl /?" below:
-OPTIMIZATION-
/O1 minimize space /O2 maximize speed
/Ob<n> inline expansion (default n=0) /Od disable optimizations (default)
/Og enable global optimization /Oi[-] enable intrinsic functions
/Os favor code space /Ot favor code speed
/Ox maximum optimizations /Oy[-] enable frame pointer omission

Related

Why is Visual Studio on Compiler Explorer ignoring the Exception Model setting?

When I try to use the /EHs flag in a Compiler Explorer testcase (to "enable" exceptions passing through extern "C" functions), VC++ 19.22 seems to be ignoring it, based on it still kicking out a C5039 and not actually changing the code.
What am I missing? Have I forgotten another switch or something?
Base case cmdline: /O1 /EHsc /Wall /wd4571
Test case cmdline: /O1 /EHs /Wall /wd4571
Ah, looks like Compiler Explorer sets the exception model itself, and this is taking precedence.

VS2015 supports magic statics, so why this warning?

I'm upgrading from VS2013 to VS2015 and am getting the following warning. I thought VS2015 implemented magic statics so that the local static object should be thread-safe, so what is going on?
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\system_error(698): error C2220: warning treated as error - no 'object' file generated
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\system_error(704): note: see reference to function template instantiation '_Ty &std::_Immortalize<std::_Generic_error_category>(void)' being compiled
with
[
_Ty=std::_Generic_error_category
]
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\system_error(698): warning C4640: '_Static': construction of local static object is not thread-safe
The error is in the system_error header from the VS installation folder. The error is in this function:
template<class _Ty> inline
_Ty& _Immortalize()
{ // return a reference to an object that will live forever
static _Immortalizer<_Ty> _Static;
return (*reinterpret_cast<_Ty *>(&_Static._Storage));
}
That's all the context there is in the error, and I can't see where system_error actually gets included.
Compiler flags are:
/Yu"stdafx.h" /GS /analyze /W3 /wd"4481" /wd"4251" /Zc:wchar_t
/Zi /Gm- /O2 /sdl /Fd"x64\Release\\Release_vc140.pdb" /Zc:inline /fp:precise
/errorReport:prompt /WX /Zc:forScope /Gd /MT /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Fp"x64\Release\MyProj.pch"
Update
Sorry, it seems fixed now. It looks like I was on the v140_xp toolset and wrong TargetPlatformVersion. This one must have slipped through the net when I thought I'd replaced them all. I'm not quite sure why getting those wrong would result in this error though. Anyway, thanks for the help so far.
It looks like its caused by the bogus warning which is turned into an Error, read this connect bug:
https://connect.microsoft.com/VisualStudio/feedback/details/2539759/c4640-warning-cannot-be-disabled
The error C2220 indicates you have enables /WX switch, which tells the compiler to treat all warnings as errors.
you can turn this warning off with:
#pragma warning (disable : 4640)
btw. unrelated, but might be usefull to You. You use _Immortalizer as a name for your class which starts with underscore followed by uppercase latter. This is prohibited by standard: read here: What are the rules about using an underscore in a C++ identifier?.
It's caused by changes in MSBuild's toolset v140_xp. Issue appears when:
project builds with VS2015 Update 2, toolset v140_xp
project configuration is Dynamic Library
project was created with ATL App Wizard, so *.vcxproj contains tag <Keyword>AtlProj</Keyword>
There is workaround: open *.vcxproj file, find tag <Keyword>AtlProj</Keyword> and replace it with <Keyword>Win32Proj</Keyword>. Nothing will be changed while compiling, but warning will disappear.
If you want to know details, navigate to the directory C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\Win32\PlatformToolsets\v140_xp, open Toolset.props and find comment <!-- Added /Zc:threadSafeInit- for ATL dll projects and enable the C4640 warnning -->. The line below it enables warning and disables "magic static" feature from C++11.
P.S. Please note that warning isn't useless: 'magic static' uses thread-local storage which suffers from ugly WindowsXP kernel bug: access to TLS from DLL causes crash when application built without TLS support. Any DLL plugins with WinXP support affected by this bug.

Visual Studio 2013 not displaying unreferenced variable warnings

I am building in Visual Studio 2013, and if I add unreferenced variables to functions, the compiler does not throw warnings about them. I tried enabling code analysis, per this thread:
Visual Studio 2013 Compiler Warnings not Showing
but that still did not fix my issue. Some additional information:
I have the warning level set to 3 (/W3), am treating warning as errors (/WX), and am in a debug build with no optimization enabled.
My full command line from Project -> Properties -> Configuration Properties -> C/C++ -> Command Line is:
/GS /analyze- /W3 /Zc:wchar_t /ZI /Gm /Od /Fd"generated\debug\intermediate\vc120.pdb" /fp:precise /D "WIN32" /D "GLEW_STATIC" /D "_DEBUG" /D "_WINDOWS" /D "_VC80_UPGRADE=0x0710" /D "_MBCS" /errorReport:prompt /WX /Zc:forScope /RTC1 /Gd /Oy- /MTd /Fa"generated\debug\intermediate\" /EHsc /nologo /Fo"generated\debug\intermediate\" /Fp"generated\debug\intermediate\blahDebug.pch"
I'm iterating on a function that I'm constantly debugging, stepping through the code, etc. -- so I know the code is being run. But if I toss "int blah = 1;" in the function and recompile, no warnings are generated.
Example code:
bool MyClass::doSomething(int someParameter)
{
int blah = 1;
// run the normal function logic here
// 'someParameter' is referenced, but 'blah' never is.
// when i compile, i receive no warning that 'blah' is unreferenced.
return true;
}
In your example code, the statement int blah = 1; both declares the variable and assigns to it. Visual Studio counts this assignment as a "reference" of the variable, thus avoiding the C4101 unreferenced local variable error that you are expecting.
To locate and remove variables which are initialized but never used, you can use a static analysis tool such as Prefast or CppCheck. There is a list of such tools here, though it may be out of date.
Note that the compiler can flag unused parameters, even if they are initialized with a default parameter. If you use warning level 4 via /W4 or /Wall, then an unused parameter will cause a C4100 unreferenced parameter warning. It is a very good idea to always build at /W4 or /Wall, rather than the default /W3.
As Ryan Bemrose outlined, static code analysis tools can be used to detect unused resources from source code.
Take a look at following function:
bool foo(int unusedParameter)
{
int unusedVariable = 1;
return true;
}
It contains two unused resources, an unused parameter and and unused but initialized local variable. Cppcheck can assist you to detect unused local variables, by using the following command:
$ cppcheck --enable=all test.cpp
Checking test.cpp...
[test.cpp:3]: (style) Variable 'unusedVariable' is assigned a value that is never used.
Currently it does not detect unused parameters.

Microsoft Visual Studio 2010 Compile for MIPS

I am trying to figure out how to compile a simple hello world in Visual Studio, but for MIPS processor. Followed the guideline posted on MS website. Only difference is I am trying this on Visual Studio 2010:
#include <iostream>
int main()
{
std::cout << "This is a native C++ program." << std::endl;
return 0;
}
Tried compiling with the /QMR4100 options:
c:\Users\ukhan\Documents\Auto_Security\Test_Code>cl /QMR4100 /EHsc forloop.cpp
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 '/QMR4100'**
forloop.cpp
Microsoft (R) Incremental Linker Version 10.00.30319.01
Copyright (C) Microsoft Corporation. All rights reserved.
/out:forloop.exe
forloop.obj
So, I checked help for options and it does seem the command line option is not valid:
c:\Users\ukhan\Documents\Auto_Security\Test_Code>cl /?
Microsoft (R) C/C++ Optimizing Compiler Version 16.00.30319.01 for x64
Copyright (C) Microsoft Corporation. All rights reserved.
C/C++ COMPILER OPTIONS
-OPTIMIZATION-
/O1 minimize space /O2 maximize speed
/Ob<n> inline expansion (default n=0) /Od disable optimizations (default)
/Og enable global optimization /Oi[-] enable intrinsic functions
/Os favor code space /Ot favor code speed
/Ox maximum optimizations
/favor:<blend|AMD64|INTEL64> select processor to optimize for, one of:
blend - a combination of optimizations for several different x64 processors
AMD64 - 64-bit AMD processors
INTEL64 - Intel(R)64 architecture processors
-CODE GENERATION-
/GF enable read-only string pooling /Gm[-] enable minimal rebuild
/Gy[-] separate functions for linker /GS[-] enable security checks
/GR[-] enable C++ RTTI /GX[-] enable C++ EH (same as /EHsc)
/EHs enable C++ EH (no SEH exceptions) /EHa enable C++ EH (w/ SEH exceptions)
/EHc extern "C" defaults to nothrow
/fp:<except[-]|fast|precise|strict> choose floating-point model:
except[-] - consider floating-point exceptions when generating code
fast - "fast" floating-point model; results are less predictable
precise - "precise" floating-point model; results are predictable
strict - "strict" floating-point model (implies /fp:except)
/Qfast_transcendentals generate inline FP intrinsics even with /fp:except
/GL[-] enable link-time code generation /GA optimize for Windows Application
/Ge force stack checking for all funcs /Gs[num] control stack checking calls
/Gh enable _penter function call /GH enable _pexit function call
/GT generate fiber-safe TLS accesses /RTC1 Enable fast checks (/RTCsu)
/RTCc Convert to smaller type checks /RTCs Stack Frame runtime checking
/RTCu Uninitialized local usage checks
/clr[:option] compile for common language runtime, where option is:
pure - produce IL-only output file (no native executable code)
safe - produce IL-only verifiable output file
oldSyntax - accept the Managed Extensions syntax from Visual C++ 2002/2003
initialAppDomain - enable initial AppDomain behavior of Visual C++ 2002
noAssembly - do not produce an assembly
/homeparams Force parameters passed in registers to be written to the stack
/GZ Enable stack checks (/RTCs)
/arch:AVX enable use of Intel(R) Advanced Vector Extensions instructions
-OUTPUT FILES-
/Fa[file] name assembly listing file /FA[scu] configure assembly listing
/Fd[file] name .PDB file /Fe<file> name executable file
/Fm[file] name map file /Fo<file> name object file
/Fp<file> name precompiled header file /Fr[file] name source browser file
/FR[file] name extended .SBR file /Fi[file] name preprocessed file
/doc[file] process XML documentation comments and optionally name the .xdc file
-PREPROCESSOR-
/AI<dir> add to assembly search path /FU<file> forced using assembly/module
/C don't strip comments /D<name>{=|#}<text> define macro
/E preprocess to stdout /EP preprocess to stdout, no #line
/P preprocess to file /Fx merge injected code to file
/FI<file> name forced include file /U<name> remove predefined macro
/u remove all predefined macros /I<dir> add to include search path
/X ignore "standard places"
-LANGUAGE-
/Zi enable debugging information /Z7 enable old-style debug info
/Zp[n] pack structs on n-byte boundary /Za disable extensions
/Ze enable extensions (default) /Zl omit default library name in .OBJ
/Zg generate function prototypes /Zs syntax check only
/vd{0|1|2} disable/enable vtordisp /vm<x> type of pointers to members
/Zc:arg1[,arg2] C++ language conformance, where arguments can be:
forScope[-] - enforce Standard C++ for scoping rules
wchar_t[-] - wchar_t is the native type, not a typedef
auto[-] - enforce the new Standard C++ meaning for auto
trigraphs[-] - enable trigraphs (off by default)
/openmp enable OpenMP 2.0 language extensions
-MISCELLANEOUS-
#<file> options response file /?, /help print this help message
/bigobj generate extended object format /c compile only, no link
/errorReport:option Report internal compiler errors to Microsoft
none - do not send report
(press <return> to continue)
prompt - prompt to immediately send report
queue - at next admin logon, prompt to send report (default)
send - send report automatically
/FC use full pathnames in diagnostics /H<num> max external name length
/J default char type is unsigned
/MP[n] use up to 'n' processes for compilation
/nologo suppress copyright message /showIncludes show include file names
/Tc<source file> compile file as .c /Tp<source file> compile file as .cpp
/TC compile all files as .c /TP compile all files as .cpp
/V<string> set version string /w disable all warnings
/wd<n> disable warning n /we<n> treat warning n as an error
/wo<n> issue warning n once /w<l><n> set warning level 1-4 for n
/W<n> set warning level (default n=1) /Wall enable all warnings
/WL enable one line diagnostics /WX treat warnings as errors
/Yc[file] create .PCH file /Yd put debug info in every .OBJ
/Yl[sym] inject .PCH ref for debug lib /Yu[file] use .PCH file
/Y- disable all PCH options /Zm<n> max memory alloc (% of default)
/Wp64 enable 64 bit porting warnings
-LINKING-
/LD Create .DLL /LDd Create .DLL debug library
/LN Create a .netmodule /F<num> set stack size
/link [linker options and libraries] /MD link with MSVCRT.LIB
/MT link with LIBCMT.LIB /MDd link with MSVCRTD.LIB debug lib
/MTd link with LIBCMTD.LIB debug lib
c:\Users\ukhan\Documents\Auto_Security\Test_Code>
Basically I am trying to generate assembly code for MIPS R4000 from Microsoft Visual C++. Any help is appreciated.
There used to be a build of the desktop version of Windows that ran on MIPS, it was discontinued in 2000 due to lack of use. Much the same happened to the mobile version, struck by an apple in 2010. Accordingly, the compiler support was discontinued as well, you need VS2008 or less.
The cross compiler in VS2008 is present in c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\ce\bin\x86_mips. A snip from the options displayed with /?:
/QMmips2 MIPS II ISA (default) /QMmips3 MIPS III ISA
/QMmips4 MIPS IV ISA /QMmips5 MIPS V ISA
/QMmips16 MIPS 16 ASE /QMmips32 MIPS 32 ISA
/QMmips64 MIPS 64 ISA
/QMn32[-] generate code for MIPS n32 mode
/QMR3900 optimize for r3900 /QMR4100 optimize for r4100
/QMR4200 optimize for r4200 /QMR4300 optimize for r4300
/QMR5400 optimize for r5400 /QMVIPER optimize for Viper
/QMRFWCE generic WinCE -QMFPE- MIPS /QMRWCE generic WinCE MIPS (Default)
/QMFPE[-] use floating point emulation /QMase3D use MIPS-3D ASE
VS2008 is still available through a reseller like Amazon, is free with an MSDN subscription or can be obtained through an auction site like Ebay. The Professional edition is required to get mobile support.

Gen code without runtime checks in VC++

How do I generate pure code (without runtime checks) in VC++ 2010 Express ? For example I removed Buffer Security Check ( set compile opt /GS-), but in my code I again saw these calls
call __security_init_cookie
...
call _RTC_CheckEsp
...
call _RTC_CheckEsp
...
How do I remove these calls?
The MSVC docs indicate that __security_init_cookie is called by the CRT runtime for "code compiled with /GS (Buffer Security Check) and in code that uses exception handling" (emphasis added). See http://msdn.microsoft.com/en-us/library/ms235362%28v=VS.100%29.aspx
I wouldn't be surprised if there's code in the runtime library itself that depends on the security cookie having been initialized, whether your code uses it or not (in other words, the runtime library code may have been compiled with /GS, and if so, it needs the cookie initialized whether or not your code does).
As for the _RTC_CheckEsp call - that should be controlled by the /RTCs or the /RTC1 option. Remove those options from your build and there should be no calls to _RTC_CheckEsp.
Disable /RTC compiler switch
http://msdn.microsoft.com/en-us/library/8wtf2dfz.aspx