简体   繁体   English

使用getenv()读取环境变量将返回NULL C ++

[英]Using getenv() to read environment variable returns NULL C++

I am attempting to read an environment variable in C++ as per this documentation . 我正在尝试根据本文档阅读C ++中的环境变量。 My code looks like this: 我的代码如下所示:

char * val;
val = getenv( "smartDir" );

ShowMessage( val );

delete val;

My problem is that val always ends up NULL as if the enviroment variable does not exist. 我的问题是,val总是以NULL结尾,就像环境变量不存在一样。 However, I clearly have the variable defined as you can see here: 但是,我清楚地定义了变量,如下所示:

在此处输入图片说明

What am I doing wrong here? 我在这里做错了什么?

  1. you should not delete pointer returned by getenv (see here , part about undefined behavior) 您不应删除getenv返回的指针(请参阅此处 ,有关未定义行为的部分)
  2. if you're changing global environment, please keep in mind, that env. 如果您要改变全球环境,请记住那个环境。 is assigned to process at its start and all child processes inherit it from parent. 在开始时被分配给进程,并且所有子进程都从父进程继承它。 So if you start program from IDE/console started before env change it will not be reflected in its child process. 因此,如果您在更改环境之前从IDE /控制台启动程序,则该程序不会反映在其子进程中。

To make testing easier: most IDEs provide 'Environment' setting under 'Debugging' settings - you can change there env passed to child process (your program) (Visual has it, QtCreator has it, C++Builder probably has it also etc.) 为了简化测试:大多数IDE在“调试”设置下提供“环境”设置-您可以更改传递给子进程(您的程序)的env(Visual拥有它,QtCreator拥有它,C ++ Builder可能也具有它等等)。 )

If you execute your program from console: use SET var=value instead of changing global env, to make local change before passing env to child process. 如果从控制台执行程序,请执行以下操作:在将env传递给子进程之前,请使用SET var=value而不是更改全局env进行本地更改。

Both solutions do not modify global env and allow to quickly test different env settings. 两种解决方案都不会修改全局环境,而是允许快速测试不同的环境设置。

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

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