using getenv and env doesn't give the same results:

冷暖自知 提交于 2019-12-11 06:09:44

问题


I have a C program that prints every environmental variable, whose name is given by stdin. It prints variables such as $PATH, $USER but it doesn't see the environmental variables that i defined myself in the Linux shell... For instance, in ~.bashrc I exported MYTEST=test_is_working, then I sourced the bashrc (source ~/.bashrc). I expected the program to return test_is_working with getenv but it doesn't.

#include <QCoreApplication>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    char* my_env= getenv("MYTEST");

    if(my_env!=NULL){
        printf("my env is : %s \n", my_env);
    }
    else {
        printf("can't find env \n");
    }
return a.exec();
}

it return : can't find env

while when I open a terminal and enter “env”, I have MYTEST=test_is_working

I saw a similar post: Using getenv function Where the solution is to launch the program from the shell. But I can't because I'm running and debugging in Qtcreator.

I don't know where I'm in the wrong, could someone explain it to me?

thanks


回答1:


  1. Environment variable are passed only to child processes which where started after setting variable. So setting them in shell will not change anything in Qt Creator and programs started from it.
  2. Qt Creator allows to customize environment variables (I've seen it).
    Check project settings (run section) and/or Qt Creator properties (it should be easy to find).
  3. you can also set program parameters in qt creator (even redirect standard streams) it is in project settings, run section.


来源:https://stackoverflow.com/questions/22220745/using-getenv-and-env-doesnt-give-the-same-results

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