Crt secure no warnings c как подключить
БлогNot. Visual C++: используем _CRT_SECURE_NO_WARNINGS для совместимости с классическими.
Visual C++: используем _CRT_SECURE_NO_WARNINGS для совместимости с классическими функциями
Часто жалуются на «неработающие» коды, особенно консольных приложений или CLR, особенно тех, что работали без каких-либо замечаний в версиях 2010-2013 и вдруг «не работают» в 2015, например, вот этот код.
Выдаются ошибки типа
Можете, как и рекомендует компилятор, заменить старые названия функций на их безопасные версии, скажем, strcpy на strcpy_s и fopen на fopen_s .
Правда, в последнем случае изменится и «классический» оператор открытия файла, скажем, с
Суть дела в том, что функции, возвращающие указатель, считаются небезопасными, отсюда и изменившийся шаблон метода открытия файла.
Есть путь ещё проще — напишите
в самом начале до всех #include .
Если используется предкомпиляция, то можно определить этот макрос в заголовочном файле stdafx.h .
Можно также попробовать «дорисовать» его не в заголовках, а в настройках проекта.
Управление предкомпилированными заголовками находится вот где: меню Проект — Свойства C/C++ — Препроцессор (Preprocessor) — Определения препроцессора (Preprocessor Definitions).
Проверено на пустом проекте C++ Visual Studio 2015, 2019, сработало.
Некоторым функциям директива «не поможет», например, stricmp всё равно придётся заменять но _stricmp , правда, без изменения списка аргументов.
Заметим, что по стандартам C++ функции strcpy , strcat и другие не устарели, это собственная политика Microsoft.
How to use _CRT_SECURE_NO_WARNINGS
I have compile error in my simple MFC window application generated from wizard with several lines of code:
error C4996: ‘strncpy’: This function or variable may be unsafe. Consider using strncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
I set Configuration Properties>>C/C++>>Preporocessor>>Preprocessor Definitions>> _CRT_NONSTDC_NO_WARNINGS
But this does’t helped. I have another very close project that generates only warning in this place and it has no _CRT_NONSTDC_NO_WARNINGS definition.
Only difference between projects is several different options in wizard.
Why _CRT_NONSTDC_NO_WARNINGS does not helps in first project and why second project compiles without problems without this definition?
SOLUTION 1 :
Configuration Properties>>C/C++>>Preporocessor>>Preprocessor Definitions>> _CRT_SECURE_NO_WARNINGS

SOLUTION 2 :
Under «Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions» add _CRT_SECURE_NO_WARNINGS
SOLUTION 3 :
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.
SOLUTION 4 :
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.
SOLUTION 5 :
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
Name already in use
cpp-docs / docs / c-runtime-library / security-features-in-the-crt.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Security Features in the CRT
Many old CRT functions have newer, more secure versions. If a secure function exists, the older, less secure version is marked as deprecated. The new version has the _s («secure») suffix.
In this context, «deprecated» means that use of the function isn’t recommended. It doesn’t mean the function will be removed from the CRT.
The secure functions don’t prevent or correct security errors. Instead, they catch errors when they occur. They do extra checks for error conditions. If there’s an error, they invoke an error handler (see Parameter validation).
For example, the strcpy function can’t tell if the string it copies is too large for the destination buffer. Its secure counterpart, strcpy_s , takes the size of the buffer as a parameter. So, it can determine if a buffer overrun will occur. If you use strcpy_s to copy 11 characters into a 10 character buffer, that’s an error on your part; strcpy_s can’t correct your mistake. But it can detect your error and inform you by invoking the invalid parameter handler.
Eliminating deprecation warnings
There are several ways to eliminate deprecation warnings for the older, less secure functions. The simplest is simply to define _CRT_SECURE_NO_WARNINGS or use the warning pragma. Either will disable deprecation warnings, but the security issues that caused the warnings still exist. It’s better to leave deprecation warnings enabled and take advantage of the new CRT security features.
In C++, the easiest way to eliminate the deprecation warnings is to use Secure template overloads. The overloads eliminate deprecation warnings in many cases. They replace calls to deprecated functions with calls to secure versions of the functions. For example, consider this deprecated call to strcpy :
Defining _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES as 1 eliminates the warning by changing the strcpy call to strcpy_s , which prevents buffer overruns. For more information, see Secure template overloads.
For those deprecated functions without secure template overloads, you should definitely consider manually updating your code to use the secure versions.
Another source of deprecation warnings, unrelated to security, is the POSIX functions. Replace POSIX function names with their standard equivalents (for example, change access to _access ), or disable POSIX-related deprecation warnings by defining _CRT_NONSTDC_NO_WARNINGS . For more information, see Compatibility.
More security features
Some of the security features include:
Parameter Validation
Secure functions, and many of their unsecure counterparts, validate parameters. Validation may include:
- Checking for NULL values.
- Checking enumerated values for validity.
- Checking that integral values are in valid ranges.
A handler for invalid parameters is also accessible to the developer. When a function encounters an invalid parameter, instead of asserting and exiting the application, the CRT allows you to check these problems via _set_invalid_parameter_handler or _set_thread_local_invalid_parameter_handler .
Sized Buffers
You must pass the buffer size to any secure function that writes to a buffer. The secure versions validate that the buffer is large enough before writing to it. The validation helps avoid dangerous buffer overrun errors that could allow malicious code to execute. These functions usually return an errno error code and invoke the invalid parameter handler if the size of the buffer is too small. Functions that read from input buffers, such as gets , have secure versions that require you to specify a maximum size.
Null termination
Some functions that left potentially non-terminated strings have secure versions, which ensure that strings are properly null-terminated.
Enhanced error reporting
The secure functions return error codes with more error information than was available with the pre-existing functions. The secure functions and many of the pre-existing functions now set errno and often return an errno code type as well, to provide better error reporting.
Filesystem security
Secure file I/O APIs support secure file access in the default case.
Windows security
Secure process APIs enforce security policies and allow ACLs to be specified.
Format string syntax checking
Invalid strings are detected, for example, when you use incorrect type field characters in printf format strings.
How to use _CRT_SECURE_NO_WARNINGS
I have compile error in my simple MFC window application generated from wizard with several lines of code:
error C4996: ‘strncpy’: This function or variable may be unsafe. Consider using strncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
I set Configuration Properties>>C/C++>>Preporocessor>>Preprocessor Definitions>> _CRT_NONSTDC_NO_WARNINGS
But this does’t helped. I have another very close project that generates only warning in this place and it has no _CRT_NONSTDC_NO_WARNINGS definition.
Only difference between projects is several different options in wizard.
Why _CRT_NONSTDC_NO_WARNINGS does not helps in first project and why second project compiles without problems without this definition?