ssroreo
ssroreo

Reputation: 127

How to set different value of same variable?

I'm writing a function that shows different result of different module. In global.h I set strModuleName:

std::string strModuleName = "no_name";

std::string GetModuleName() {
    return strModuleName;
}

And in module1.h, I set module name to "module1":

#include "global.h"

strModuleName = "module1";
...
void some_function() {
    GetModuleName();  //I want to get "module1"
}

in module2.h ,set module name to "module2":

#include "global.h"

strModuleName = "module2";
...
void some_function2() {
    GetModuleName();  //I want to get "module2"
}

But it's a redefinition error. Is there any way to make it?

Upvotes: 0

Views: 65

Answers (1)

MSalters
MSalters

Reputation: 179819

"In global.h I set strModuleName"

To be precise, you define and initialize strModuleName in global.h.

And global.h is #include'd twice. So you also have two definitions and two initializations. That's not possible.

You also have a double definition of GetModuleName.

In header module1.h, you have no reasonable control about how often other files will include you. So you can't reasonably define variables there either. Additionally, you can't have assignment statements like strModuleName = "module1"; outside functions.

What you can do:

// module1.h
namespace module1 {
  inline auto GetModuleName() {
    return "Module1";
  }
}

The namespace allows you to define GetModuleName, because the full name module1::GetModuleName will differ from module2::GetModuleName.

The inline tells the compiler that there can be multiple definitions of this function (due to module1.h being included in multiple translation units)

Upvotes: 1

Related Questions