先来看下面的code:
==============================
#include <string.h>
#include <io.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
open("a.txt", O_TEXT);
char c[30] = { 0 };
strcpy(c, "hihi~");
return 0;
}
==============================
vs2005编译结果:
1>.....\main.cpp(6) : warning C4996: 'open': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _open. See online help for details.
1> c:\program files\microsoft visual studio 8\vc\include\io.h(328) : see declaration of 'open'
1>.....\main.cpp(8) : warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1> c:\program files\microsoft visual studio 8\vc\include\string.h(74) : see declaration of 'strcpy'
用vs2005的应该都碰到过的. 下面来逐一分析, vs2005的新library为什么会有这个warning以及对于cross-platform的影响.
*) strcpy() --> strcpy_s()
这是一个security的扩展函数, 后者比前者多了一个buffer的大小参数. 如果buffer overflow的话, 据说是会有特别的error handler, 默认的strcpy()则直接告诉你access violation.
关于这个东西还有一堆的macro用来控制, 还非常的难记. 所以这个扩展其实并没有很大的用处.
*) open() --> _open()
open()是POSIX标准的兼容函数, 而_open()则不是, 而且放到linux下编译是绝对通不过的.
那为什么还说是“ISO C++ conformant”呢? 这里有篇帖子非常的详细, 主要的发言人P.J. Plauger就是当初实现C语言的几个人之一.
大概意识就是说: 原来的open()确实是为了调用的方便, 就像普通的函数一样. 现在iso标准说, global的函数统统都要用"_"来开头, 所以M$就照做了, 还加了这个warning. 可是我觉得还是没有必要的=v=... 严重妨碍cross-platform.
看CRT的源码, 其实M$一直实现的都是_open()这个函数, open()一直只是一个函数原型. 最后也没有typedef一把, 而是通过一个linker的trick来实现(__cdecl的calling convention).
总之, 我决定无视这两个warning, 直接#pragma warning(disable: 4996) 就一切清净了.



