gpt4 book ai didi

c - 在 C 中读取环境变量时出错

转载 作者:可可西里 更新时间:2023-11-01 11:12:24 24 4
gpt4 key购买 nike

我正在尝试读取 Windows 平台上的环境变量。我将变量设置为全局变量,因为我打算通过各种函数使用它。这是我试过的

#include <stdlib.h>
#include <malloc.h>
#include <string.h>

char* devset = getenv("DEVSET"); //1 for debugging, 0 for normal execution

我得到了错误

C:\Users\Prateek\Documents\Script Parser\main.c|6|error: initializer element is not constant

我在 main 中尝试了同样的事情,它编译并且我没有得到任何错误。但是,通过这种方式,我将需要将环境变量作为参数传递给所有函数。是否有另一种方法可以使环境变量全局可访问?任何帮助表示赞赏。

最佳答案

问题不在于读取环境变量,而在于你执行它的地方。您的代码在静态初始化程序中读取变量,这是不允许的:只能在那里使用编译时常量。

However this way I will be required to pass the environmental variable as an argument to all the functions

不,您不会:将变量保留在全局范围内,并将您的代码移至 main 以解决问题:

char* devset;
int main(int argc, char *argv[]) {
devset = getenv("DEVSET"); //1 for debugging, 0 for normal execution
....
return 0;
}

关于c - 在 C 中读取环境变量时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29588144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com