0

I am dealing with something mysterious or I am not thinking straight. Details are below, I held off on all usings-s, #include-s, etc. in favor of brevity. My code compiles fine.

Pseudo Code:

File: Constants.hpp

namespace TestConstants
{
  const std::string TEST = "Test";
}

File: Program.cpp

#include "Constants.hpp"

void Program::Foo()
{
 // do something with TestConstants::TEST here.
}

File: ProgramTest.cpp

#include "Program.hpp"

BOOST_FIXTURE_TEST_CASE(SomeTest, TestFixture)
{
   Program p;
   p.Foo();
}

Problem: When I run the test, TestConstants::TEST string is initialized to "" in Program::Foo(), while if I hit Ctrl+F5 the string constant contains the expected value and the code runs just fine. I verified this by debugging in both the cases. If I try accessing the string constant in the test itself, it is properly initialized but still empty when I get into Program::Foo().

I am using Visual Studio on a Windows 10 machine.

The test itself doesn't do any kind of set-up, let alone messing with constant strings. I am kind of clueless as to what I could be missing.

  • Try to use it in a main insteed of a testcase. There could be any issue with initialisation order, which means that you code is running before the initialisation. – gerum Feb 23 '21 at 08:36
  • If you use C++17, you could try to use the `inline` keyword for `TEST`, like this: `inline const std::string TEST = "Test";` – therealcain Feb 23 '21 at 08:38
  • Which environment do you use? OS, compiler version etc??? – U. W. Feb 23 '21 at 08:46
  • 1
    Oh, would `constexpr` instead of `const` help? – U. W. Feb 23 '21 at 13:39
  • @U.W. constexpr helped. I think I am going to go with it, can't explain what could be wrong with const string nonetheless. I suspect something to do with the sequence of string initializations. – Aniruddha Gore Feb 23 '21 at 17:45

1 Answers1

0

U.W.'s suggestion to use consexpr auto helped. I am not sure what's wrong with std::string but for now constexpr would do.