Home > front end >  How to use non-const global variable that defined in a namespace
How to use non-const global variable that defined in a namespace

Time:01-19

I have an header file that i put some global const variables. Now I need another project wide modifiable variable. But it gives linker error as expected. I am trying to solve the issue without using inline keyword. My codes:

constants.h:

#ifndef CONSTANTS_H
#define CONSTANTS_H

namespace constants {
    bool myVar;
}

#endif // CONSTANTS_H

I am using this variable in my classes with constants::myVar. And I got a linker error. Any solution without using inline (for backward compiler compability)?

CodePudding user response:

I completely agree with the comments above about looking at alternatives for this design. Also as you seems to be aware, c 17 inline variables offer a better solution.

Having said that, if you must keep the current design - you can do the following:

  1. Change the header file to declare myVar as extern:

    namespace constants {
    //--vvvvvv------------
        extern bool myVar;
    }
    
  2. Add constants.cpp file (if it doesn't exists yet), with a definition for myVar (preferably with some initialization):

    namespace constants {
        bool myVar;
        // or better: something like:
        bool myVar = false;
    }
    
  • Related