1. 程式人生 > >C4995 錯誤或警告的解決辦法

C4995 錯誤或警告的解決辦法

使用Visual Studio 2008寫程式碼時,編譯時遇到警告:

1
2
3
4
5
6
7
8
9
1>d:\program\msvs2008\vc\include\cstdio(49) : warning C4995: 'gets': name was marked as #pragma deprecated
1>d:\program\msvs2008\vc\include\cstdio(53) : warning C4995: 'sprintf': name was marked as #pragma deprecated
1>d:\program\msvs2008\vc\include\cstdio(56) : warning C4995: 'vsprintf': name was marked as #pragma deprecated
1>d:\program\msvs2008\vc\include\cstring(22) : warning C4995: 'strcat': name was marked as #pragma deprecated
1>d:\program\msvs2008\vc\include\cstring(23) : warning C4995: 'strcpy': name was marked as #pragma deprecated
1>d:\program\msvs2008\vc\include\cwchar(36) : warning C4995: 'swprintf': name was marked as #pragma deprecated
1>d:\program\msvs2008\vc\include\cwchar(37) : warning C4995: 'vswprintf': name was marked as #pragma deprecated
1>d:\program\msvs2008\vc\include\cwchar(39) : warning C4995: 'wcscat': name was marked as #pragma deprecated
1>d:\program\msvs2008\vc\include\cwchar(41) : warning C4995: 'wcscpy': name was marked as #pragma deprecated

意思是說,某個函式已經被標記為過時了,最好不要用,在將來的版本中,該函式可能就沒有了,不存在了。

奇怪的是,程式碼裡面並沒有使用這些函式啊。但是先不考慮這個了,還是看看如何解決吧。對於編譯器警告,當然可以用 #pragma warning(disable: xxxx ) 的語法將其禁止掉,這樣編譯時編譯器就不會在那裡唧唧歪歪了。在網上查詢此類問題,基本上都是這樣說的。

然後仔細想想,關閉這個警告並不正常,因為這樣一來,所有過時的函式都不會再警告了,而我們可能是需要這個警告的,像是對於strcpy這種超常用的函式,考慮到安全性(應對緩衝區溢位攻擊),我們的確應該使用其安全版本,例如strcpy就有對應的StringCchCopy/StringCbCopy這樣的函式,如果關閉了此警告,我們就可能在程式碼中不小心寫下strcpy,而不是其對應的安全版本(當然,strcpy等函式是特例,關閉C4995警告後,仍然會有其他警告,下面有說明)。

所以,考察上述幾個函式,我們知道其函式宣告所在的標頭檔案,這些標頭檔案中的函式應該都不會用到,所以可以用另一種方式來避免引入這些標頭檔案:

在你的工程的預編譯標頭檔案(一般來說,就是stdafx.h)中,在 #pragma once 一行後面加上下列三行:

1
2
3
#define _CSTDIO_
#define _CSTRING_
#define _CWCHAR_

這樣,編譯器就不會再載入 cstdio / cstring / cwchar 這幾個標頭檔案了。

P.S.
使用 #pragma warning(disable: xxxx) 這種方式關閉警告後,如果程式碼裡面用到了 strcpy 這樣的函式,編譯器會報另一個警告:

1
2
1>e:\work\ncksoft\test\main.cpp(126) : 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>d:\program\msvs2008\vc\include\string.h(74) : see declaration of 'strcpy'

所以我們仍然可以得到想要的警告資訊。