Bùi Văn Thủ
Bùi Văn Thủ

Reputation: 393

How to prevent auto optimization from for loop to memset() in Visual Studio?

I'm developing a program without using CRT , so, some third party using very naive implementation of memset() likes:

char x[10];
for(int i= 0; i< 10; i++) {
  x[i] = '\0';
}

It's alot of this type of code in that 3rd party library, and, I do not like messing around with it, so, how could I prevent Visual Studio from automatically converting from for loop to memset() ?

Edit: Why this is a problem ? Since, my program does not use CRT, so, if Visual Studio auto converts the for loop to memset(), it will cause the error:

Unresolved external symbol _memset

Upvotes: 7

Views: 1313

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148860

If I correctly remember, MSVC used to have an option for explicitely not use the C run time library. My version was not English, but it should be something like: Use standard libraries. It was used to produce an executable with no dependancies beyond Windows API, which is your current requirement.


According to the MSVC page about NODEFAULTLIB, the option still exists on recent versions and should do what you need:

If you use /NODEFAULTLIB, for example, to build your program without the C run-time library, you may have to also use /ENTRY to specify the entry point (function) in your program.

I could not test (no access to a MSVC installation), but I would bet a coin that MSVC will not try to use a function from the CRT when you set this option.


IMHO, MSVC should not optimize the loop to a memset call, because it defeats a stand alone environment build. Anyway, a possible workaround is to provide à private memset version wrapping the WinAPI function ZeroMemory.

Upvotes: 0

Eric Postpischil
Eric Postpischil

Reputation: 222244

The only relevant compiler option I see in the list of compiler options, besides disabling optimization, is /kernel, which produces a binary that can run in the Windows kernel. That is a big hammer; it alters compilation in several ways. Building for the kernel is something one might expect would instruct the compiler not to use library routines. However, the specific page for that switch does not mention it, so I doubt the switch includes that.

Given this, I do not think Visual Studio has a feature of producing stand-alone code that does not use library routines.

Upvotes: 3

Related Questions