I have one header file where I am declaring variables like below :
//Constants.h
const std::string& binaryName = "ApplicationGateway";
const std::string& binaryMode = "Maintenance";
However when i include this file in multiple cpp files say first.cpp and second.cpp i get multiple definition error and i could not find the reasoning for same because my understanding is const variable have internal linkage.
So my question is does const reference don't have internal linkage and if not how we can have const reference in header file that need to be included in multiple cpp files.
You should define them in Constants.cpp and mark them as extern in your header:
//Constants.cpp
const std::string& binaryName = "ApplicationGateway";
const std::string& binaryMode = "Maintenance";
//Constants.h
extern const std::string& binaryName;
extern const std::string& binaryMode;
Think of header files as being copied and pasted into everywhere you include said header file. That is why the compiler thinks you are declaring the variables over and over again, because to the compiler, the variables actually are. A quirk of this (though terrible design) is that if you were to keep it in your header, but only ever include it anywhere once, then your code should compile fine.