0

The back trace stack is listed. We just call the getenv(), gnu libc version is 2.17 .

(gdb) bt
#0  0x00007ffff6c59b71 in __strlen_sse2 () from /lib64/libc.so.6
#1  0x00007ffff6c0b036 in getenv () from /lib64/libc.so.6
#2  0x0000000000e23f5e in AdsProperties::AdsProperties (this=0x184ad60 
    <config>) at XXXXXX
#3  0x0000000000a3d355 in __static_initialization_and_destruction_0 
    (__initialize_p=1, __priority=65535)at XXXXXXXX
#4  0x0000000000a3d499 in _GLOBAL__sub_I_server_main.cpp(void)
#5  0x0000000000eff50d in __libc_csu_init ()
#6  0x00007ffff6bf4ac5 in __libc_start_main () from /lib64/libc.so.6
#7  0x000000000077b6e9 in _start ()

The code is like this:

const std::string NAME_ENV_KEY("NAME");
char const* name = getenv(NAME_ENV_KEY.c_str());

And the NAME environment is setted.

peterh
  • 11,875
  • 18
  • 85
  • 108

1 Answers1

0

For global constructors (and destructors) the order of construction is undefined. In your case, the pointer constructor is probably called before the string constructor. You can solve this by creating an instance of a 'global' class (for example CMyLoader) where you control the construction order.

CMyloader::CMyloader()
{
    const std::string NAME_ENV_KEY("NAME");
    m_name = getenv(NAME_ENV_KEY.c_str());
}
CMyloader myLoader;

You can also process in a single step :

char const* name = getenv(NAME_ENV_KEY("NAME").c_str());
  • You are absolutely right. The variable NAME_ENV_KEY is a static const member of a class: ClassA (defined in class_a.h, likely), and the assignment of this variable is in the file class_a.cpp. Then we first compile class_a.cpp & class_a.h to class_a.a. Then the main.cpp calls the constructor of ClassA. I think when we call the constructor of ClassA, the assignment of NAME_ENV_KEY cannot be executed. – Wenjiao Liao Aug 03 '17 at 06:37