c - 为什么Windows和Linux有不同的strdup实现: strdup() and _strdup()?

标签 c cross-platform posix

在 Windows 上使用 strdup 时,我发现 _strdup 是 Windows 特定的,但是当我在 Linux 上运行相同的代码时,它需要 strdup > 没有下划线。有谁知道这种差异背后的历史,以及有关您在编写跨平台代码时如何处理此问题的一些信息?

最佳答案

有几个函数是 POSIX 规范(即 Linux 和大多数其他 UNIX 变体)的一部分,但它们不是标准 C 的一部分。其中包括 strdupwrite阅读以及其他。

前导下划线的原因如下,取自MSDN docs :

The Universal C Run-Time Library (UCRT) supports most of the C standard library required for C++ conformance. It implements the C99 (ISO/IEC 9899:1999) library, with certain exceptions: The type-generic macros defined in , and strict type compatibility in . The UCRT also implements a large subset of the POSIX.1 (ISO/IEC 9945-1:1996, the POSIX System Application Program Interface) C library. However, it's not fully conformant to any specific POSIX standard. The UCRT also implements several Microsoft-specific functions and macros that aren't part of a standard.

Functions specific to the Microsoft implementation of Visual C++ are found in the vcruntime library. Many of these functions are for internal use and can't be called by user code. Some are documented for use in debugging and implementation compatibility.

The C++ standard reserves names that begin with an underscore in the global namespace to the implementation. Both the POSIX functions and Microsoft-specific runtime library functions are in the global namespace, but aren't part of the standard C runtime library. That's why the preferred Microsoft implementations of these functions have a leading underscore. For portability, the UCRT also supports the default names, but the Microsoft C++ compiler issues a deprecation warning when code that uses them is compiled. Only the default names are deprecated, not the functions themselves. To suppress the warning, define _CRT_NONSTDC_NO_WARNINGS before including any headers in code that uses the original POSIX names.

我通过使用 #define 来处理这个问题,它检查程序是否正在为 Windows 编译,如果是,则创建另一个 #define 来映射 POSIX 名称为 Windows 特定名称。您可以检查几个选项,但最可靠的可能是 _MSC_VER,它是在 MSVC 是编译器时定义的。

#ifdef _MSC_VER
#define strdup(p) _strdup(p)
#endif

关于c - 为什么Windows和Linux有不同的strdup实现: strdup() and _strdup()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60154748/

相关文章:

c++ - 使用CMake生成Visual Studio 2015 Makefile项目(GDB)

c++ - 如何在跨平台应用中使用QtWinExtras

c - 是否有可能以某种方式在 Docker 容器之间或容器与主机之间使用 POSIX 信号量?

C - 不回显 system() 命令

c++ - 在 UTF-8 内部工作然后仅在 Windows 需要时才转换为 UTF-16 是否有任何危险?

linux - 确定 Linux 下的标准文件位置

c++ - 如何关闭 POSIX 函数 send() 中的 TCP PSH 标志?

c - 将单词保存到 C 中的链表的问题

C - 用户输入数字的所有数字组合

连接字符串 - 你如何以一种干净的方式做到这一点?