如何使用_CRT_SECURE_NO_WARNING

在我的简单 MFC 窗口应用程序中,我用几行代码从向导生成了一个编译错误:

Error C4996: ‘ strncpy’: 此函数或变量可能不安全。考虑改用 strncpy _ s。若要禁用弃权,请使用 Use _ CRT _ SECURE _ NO _ WARNING 使用 _ CRT _ SECURE _ NO _ 警告。有关详细信息,请参阅在线帮助。

我设置了 Configuration Properties>>C/C++>>Preporocessor>>Preprocessor Definitions>> _CRT_NONSTDC_NO_WARNINGS

但这没有帮助。我有另一个非常接近的项目,只在这个地方生成警告,它没有 _CRT_NONSTDC_NO_WARNINGS的定义。

在向导中,项目之间只有几个不同的选项。

为什么 CRT _ NONSTDC _ NO _ WARNIES 在第一个项目中没有帮助,为什么第二个项目在没有这个定义的情况下编译没有问题?

394189 次浏览

Add by

Configuration Properties>>C/C++>>Preporocessor>>Preprocessor Definitions>> _CRT_SECURE_NO_WARNINGS

screenshot of the relevant config interface

Under "Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions" add _CRT_SECURE_NO_WARNINGS

If your are in Visual Studio 2012 or later this has an additional setting 'SDL checks' Under Property Pages -> C/C++ -> General

Additional Security Development Lifecycle (SDL) recommended checks; includes enabling additional secure code generation features and extra security-relevant warnings as errors.

It defaults to YES - For a reason, I.E you should use the secure version of the strncpy. If you change this to NO you will not get a error when using the insecure version.

SDL checks in vs2012 and later

Adding _CRT_SECURE_NO_WARNINGS to Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions didn't work for me, don't know why.

The following hint works: In stdafx.h file, please add

#define _CRT_SECURE_NO_DEPRECATE

before include other header files.

For a quick fix or test, I find it handy just adding #define _CRT_SECURE_NO_WARNINGS to the top of the file before all #include

#define _CRT_SECURE_NO_WARNINGS
#include ...
int main(){
//...
}

I was getting the same error in Visual Studio 2017 and to fix it just added #define _CRT_SECURE_NO_WARNINGS after #include "pch.h"

#include "pch.h"
#define _CRT_SECURE_NO_WARNINGS
....

Visual Studio 2019 with CMake

Add the following to CMakeLists.txt:

add_definitions(-D_CRT_SECURE_NO_WARNINGS)