سؤال

Today I stumbled to MSDN's documents about Visual C++'s C runtime (example: http://msdn.microsoft.com/en-us/library/8syseb29.aspx) and find to my surprise a lot of functions that look just like POSIX syscalls: dup2, fdopen, stat, execlp, ..., except being prefixed with _ or _w. Are these functions just wrappers to Windows API? Are they only usable with the POSIX subsystem? Are they deprecated/going to be deprecated?

هل كانت مفيدة؟

المحلول

These functions are wrappers around Win32 APIs. You don't need to have the POSIX subsystem to use them. They are not likely to disappear - Microsoft takes backwards compatibility very seriously.

You can find the source code of the MS CRT in "\Program Files (x86)\Microsoft Visual Studio X.0\VC\crt\src". E.g. you can see that _dup2 is calling DuplicateHandle and _stat is using FindFirstFileEx.

As for why they got the underscores, I could not find an official reason, but I suspect it's probably because these functions don't provide full POSIX compliance.

نصائح أخرى

It is important to know that some of the non-underscored functions are part of the C standard (e.g, fwrite is specified in C11, §7.21.8.2), while others are specified in the POSIX standard, and are not part of the C standard (e.g. strdup).

Now Windows is not 100% POSIX-compliant, so these POSIX-like functions may or may not behave according to the POSIX specification. It is quite possible that some C application that relies on POSIX behavior of these functions may compile but not run on Windows or run but work incorrectly.

To try to prevent this, MSVC greets you with a warning every time you try to use them:

warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup. See online help for details.

Now, although this sounds like _strdup is standardized by ISO, it is not; it's just weaselease for "Each name that begins with an underscore is reserved to the implementation", [lib.global.names]/2.

Microsoft is basically offering you another name, _strdup, which does not come with the POSIX baggage attached to it. You probably won't find it on any other platform, though.

In the end, there is only one implementation, _strdup, the linker simply maps strdup to _strdup (see oldnames.lib).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top