0

My understanding is that anonymous namespaces are an idiomatic c++ way of solving certain problems (i.e. what C# and Java solve with static classes).

In the following example, I am attempting to access a std::string which is declared in an anonymous namespace, but I get a compile-time error that aString "does not name a type"

I have tried changing the line in question to std::string aString = "some text";, but this results in the compiler complaining that aString is ambiguous.

Is it possible to forward declare a variable in an anonymous namespace like this?

#include <iostream>
#include <string

namespace{
    std::string aString;
}

aString = "some text";

int main()
{
    std::cout << "aString = " << aString << std::endl;
    return 0;
}
wesanyer
  • 982
  • 1
  • 6
  • 27
  • 1
    TL;DR of the dupe: You can't run arbitrary code in the global space. `aString = "some text";` is an assignment so that needs to be done in block scope. – NathanOliver Oct 25 '19 at 18:47
  • You could initialize your string, though: `std::string aString("some text");` – Fred Larson Oct 25 '19 at 18:48
  • So after initializing it, the only way to modify `aString` is through some function that's defined in the same translation unit? – wesanyer Oct 25 '19 at 18:51
  • @wesanyer Yes. You can't run code in the global space. All you can do is declare and define things and if you do define a variable you can initialize it as part of the definition. – NathanOliver Oct 25 '19 at 18:56
  • @wesanyer Yes. You can't run code in the global space. All you can do is declare and define things and if you do define a variable you can initialize it as part of the definition. – NathanOliver Oct 25 '19 at 18:56
  • You can't run arbitrary code in *any* namespace. Most code is only allowed to appear inside a function. – Brian Bi Oct 25 '19 at 19:06
  • Ok. Thank you all for the help and for identifying this as a duplicate. – wesanyer Oct 25 '19 at 19:17

0 Answers0