C++17 what new with : error C4996: 'getenv': This function or variable may be unsafe. Consider using _dupenv_s instead

Viewed 2296

i try to do a simple task and get environment variable both in Linux and windows all docs point to use : std::getenv but when i run the compilation in windows 10 using visual studio 2019 I'm getting :

error C4996: 'getenv': This function or variable may be unsafe. Consider using _dupenv_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS

This is the function :

std::string Utils::getEnvVar(std::string const& key)
{
    char* val = std::getenv(key.c_str());
    return val == NULL ? std::string("") : std::string(val);
}

i found only this thread , which i don't understand what is the solution for cross-platform solution.

1 Answers

The compiler message says it all:

error C4996: 'getenv': This function or variable may be unsafe. Consider using _dupenv_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS

The warnings is MSVC specific. It warns about usage of an unsafe C standard function.

If you only need to compile on MSVC, then

Consider using _dupenv_s instead.

If you need cross platform compatibility, then

To disable deprecation, use _CRT_SECURE_NO_WARNINGS

Which is a define, so just #define _CRT_SECURE_NO_WARNINGS. Another solution would be to disable the warning (#pragma warning(disable: 4996)).

See also Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio.

Related