C++: Setenv(). Undefined identifier in Visual Studio

喜你入骨 提交于 2019-11-27 03:24:32

问题


Look my code seems to be correct, according to all the documentation I can find online. My IDE is MS Visual Studio Xpress 4 Windows Desktop 2012, and it's compiler is throwing up the error:

Error 1 error C3861: 'setenv': identifier not found e:\users\owner\documents\visual studio 2012\projects\project1\project1\source1.cpp 18 1 Project1.

Help me!!!

#include <windows.h>
#include <sstream>
#include <ostream>
#include <cstdlib>
#include <iostream>
#include <stdlib.h>

using namespace std;

int howManyInClass = 0;
int main(){

long checklength = sizeof(getenv("classSize"))/sizeof(*getenv("classSize"));
if (checklength==0){
    cout<<"Please enter the ammount of students in your class";
    cin>> howManyInClass;
    cin.ignore();
    setenv("classSize", howManyInClass, 1);}

};

回答1:


You can either use _putenv() which takes a string parameter as the string classSize=7;

ostringstream classSize;
classSize << "classSize=" << howManyInClass;
_putenv(classSize.str().c_str());

...or (preferably) the security enhanced _putenv_s() that takes the key and the value as separate (const char*) parameters;

ostringstream classSize;
classSize << howManyInClass;
_putenv_s("classSize", classSize.str().c_str());



回答2:


Microsoft's runtime library doesn't support the standard setenv() function. You could use their replacement _putenv() or, for portable code, I prefer to use a simple wrapper.

Here's my wrapper with the standard interface:

int setenv(const char *name, const char *value, int overwrite)
{
    int errcode = 0;
    if(!overwrite) {
        size_t envsize = 0;
        errcode = getenv_s(&envsize, NULL, 0, name);
        if(errcode || envsize) return errcode;
    }
    return _putenv_s(name, value);
}



回答3:


Try _putenv instead of setenv.

msdn _putenv




回答4:


the reason you encountered the linkage error is that, if you take a look at the content of the library of stdlib.h, you will find that, setenv() is not declared there. At the first glance, it is a C standard API, but looks like Windows do not follow all of the standard. Or, you might be able to configure your VS to use CRT instead of Windows runtime, in that case, I think setenv will be identified.



来源:https://stackoverflow.com/questions/17258029/c-setenv-undefined-identifier-in-visual-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!