简体   繁体   English

C ++ getenv总是返回null值

[英]C++ getenv always returns null value

I have just added the environment variable "DataDir", but the getenv function still returns null value. 我刚刚添加了环境变量“DataDir”,但getenv函数仍然返回null值。

Here is my code: const char *ret = getenv("DataDir"); 这是我的代码:const char * ret = getenv(“DataDir”);

I restarted my computer and it done. 我重新启动了电脑,完成了。

did you remember to export the variable before running the program? 你还记得在运行程序之前导出变量吗? If you are using bash shell on linux, for example, you generally should use export DataDir="..." 例如,如果你在linux上使用bash shell,你通常应该使用export DataDir="..."

On windows, if you set the environment variables using the system settings window, it will not immediately propagate to all of the running programs. 在Windows上,如果使用系统设置窗口设置环境变量,它将不会立即传播到所有正在运行的程序。 If "I restarted my computer and it done." 如果“我重新启动计算机并完成了”。 means "restarting the computer resolved the issue", then I believe that explains the problem. 意思是“重新启动计算机解决了问题”,然后我相信这解释了问题。 After changing the environment variable, try closing all programs and then start a CMD session (or visual studio) and run the program again 更改环境变量后,尝试关闭所有程序,然后启动CMD会话(或visual studio)并再次运行该程序

Are you running on Windows? 你在Windows上运行吗? Did you set the environment variable through the control panel? 您是否通过控制面板设置了环境变量? If so, that only affects processes that you start (programs that you launch) after you changed the setting. 如果是这样,那么只会影响您更改设置启动的进程(启动的程序)。 If you're running from a command prompt, and the command prompt didn't inherit the new environment variable, then your program won't inherit it either. 如果您从命令提示符运行,并且命令提示符未继承新的环境变量,那么您的程序也不会继承它。

After rebooting, all new processes inherit the new environment variable. 重新启动后,所有新进程都将继承新的环境变量。

On the other hand, if you set the variable and then run the program: 另一方面,如果设置变量然后运行程序:

C:\>set DataDir=blah
C:\>.\my_program

then your program will inherit the variable (but it won't persist across a reboot). 然后你的程序将继承变量(但它不会在重新启动时持续存在)。

Similar considerations apply on Linux and other systems, but the details differ. 类似的考虑适用于Linux和其他系统,但细节不同。

Note that I'm only guessing, based on the symptoms you reported, what system you're using. 请注意,我只是根据您报告的症状猜测您正在使用的系统。 In the future, it would be helpful to provide that information in the question (if it's not relevant we can ignore it). 将来,在问题中提供这些信息会有所帮助(如果不相关,我们可以忽略它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM