I am trying to create a global instance of a class whose constructor refers to a global variable.
The program compiles without errors. But when it starts, it is reset by reference to a global variable.
How to create a global instance of this class without destroying its constructor?
Here is the SSCCE I made:
#include "TestClass.h"
-
#ifndef C_H_INCLUDED #define C_H_INCLUDED #include <string> // global extern const std::string S; #endif // C_H_INCLUDED
-
#include "Ch" #include <string> // extern definition of global const std::string S = "global string data";
-
#ifndef TESTCLASS_H_INCLUDED #define TESTCLASS_H_INCLUDED class TestClass { public: TestClass(); }; #endif
-
#include "TestClass.h" #include <iostream> #include "Ch" // for S global TestClass::TestClass() { std::cout << S << std::endl; // this line crashes the program }
Debugger Debug Messages:
Program received signal SIGSEGV, Segmentation fault. In std::basic_ostream<char, std::char_traits<char> >& std::operator<< <char, std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) () () #1 0x004014f9 in TestClass::TestClass (this=0x4a0024 <j>) at E:\cpp\externconsttest\TestClass.cpp:9 E:\cpp\externconsttest\TestClass.cpp:9:117:beg:0x4014f9 At E:\cpp\externconsttest\TestClass.cpp:9 #1 0x004014f9 in TestClass::TestClass (this=0x4a0024 <j>) at E:\cpp\externconsttest\TestClass.cpp:9 E:\cpp\externconsttest\TestClass.cpp:9:117:beg:0x4014f9
This example crashes in the <<statement, but it crashes with any reference to S no matter how it refers.
source share