I've created a minimal example to share a variable between classes.
In C# normally I do this by creating a public static class with a public static variable... then I can just access it from everywhere.
Main.cpp
#include <iostream>
#include "TestClass.h"
#include "Shared.h"
int main(int argc, char* argv[])
{
std::cout << "This should print 'Hello'" << std::endl;
std::cout << "Print 1 from main: " << MyNameSpace::MESSAGE << std::endl;
std::cout << "This should print 'Test message 1'" << std::endl;
TestClass test("Test message 1");
std::cout << "Print 2 from main: " << MyNameSpace::MESSAGE << std::endl;
std::cout << "This should print 'Test message 2'" << std::endl;
MyNameSpace::MESSAGE = "Test message 2";
std::cout << "Print 3 from main: " << MyNameSpace::MESSAGE << std::endl;
return 0;
}
Shared.h
#pragma once
#include <string>
namespace MyNameSpace
{
static std::string MESSAGE = "Hello";
}
TestClass.h
#pragma once
#include <string>
#include "Shared.h"
#include <iostream>
class TestClass {
public:
TestClass(const std::string& message);
};
TestClass.cpp
#include "TestClass.h"
TestClass::TestClass(const std::string& message)
{
MyNameSpace::MESSAGE = message;
std::cout << "Print 1 from TestClass: " << MyNameSpace::MESSAGE << std::endl;
}
So, if I set any value, for example MyNameSpace::MESSAGE = "Potato"
from any file/class, I want to see Potato in MyNameSpace::MESSAGE
from all classes
Here is the output so you can see better:
C:\Users\Adrian\RiderProjects\Test\x64\Debug\Test.exe
Hello:
Print 1 from main: Hello
This should print Test message 1:
Print 1 from TestClass: Test message 1
Print 2 from main: Hello
Test message 2:
Print 3 from main: Test message 2
Process finished with exit code 0.
CodePudding user response:
Note that in C you can define public static variables in classes, and they will pretty much do what you want.
That said, use of namespaces here is almost irrelevant. It essentially means that there's a ::
in the name of your variable (MyNamespace::MESSAGE
), but you could alternatively call your variable MyNamespace_MESSAGE
, for example.
So the question, independent of namespaces, is how can you have a global variable in C . One way do to this is to declare the variable in a header file, and define it in a single C file. For example:
// message.h
extern std::string message;
// message.cc
std::string message {"Hello"};
(Wrap these in a namespace if you want.) Alternatively, if you just want to put it in a header file, use:
// header.h
inline std::string message{"Hello"};
Outside of a class, static
just means static linkage, meaning that you can't access the variable from other translation units. That's not what you want.