Using C++14, I'm trying to define a variable in a namespace where commonly used variables are stored (App::Common). The main function should be the one that sets it, since it gets set to argv[0]. Meanwhile I need the variable to be visible by all other classes/files. But I get the linker error shown below. Also, ideally I would like the variable to be const where only the main function would set it once.
common.hpp
#pragma once #include <string> namespace App{ namespace Common{ extern std::string appPath; } } main.cpp
#include "common.hpp" #include "client.hpp" #include <string> int main() { App::Common::appPath = argv[0]; } client.hpp
#include "common.hpp" class Client { public: void printAppPath(); }; client.cpp
#include <iostream> #include <string> #include "common.hpp" #include "client.hpp" void Client::printAppPath() { std::cout << App::Common::appPath << std::endl; } I get the following error by the linker:
ld: main.o: in function `main': main.cpp:(.text.startup.main+0x25): undefined reference to `App::Common::appPath[abi:cxx11]' ld: Client.o: in function `Client::printAppPath()': Client.cpp:(.text...): undefined reference to `App::Common::appPath[abi:cxx11]'