Search code examples
c++mongodbinstancemongo-cxx-drivermongodb-c

Mongocxx accessing Error from different cpp file


I have created a header mongo.h it contain

mongocxx::instance inst{};
mongocxx::uri uri{ "link*****" };
mongocxx::client client{ uri };

i accessed the mongodb from main.cpp by including this mongo.h but when including this header to other cpp file it return error.

Documents saying that the instance must create once . i have read http://mongocxx.org/api/current/classmongocxx_1_1instance.html not understand fully, i dont familiar with constructor and destructor ,, Any body please help to access mongodb from every cpp file .


Solution

  • This is a good example of where a singleton could help. In mongo.h, put a single function declaration:

    mongocxx::client& get_client();
    

    In a single cpp file, define the function as follows:

    mongocxx::instance inst{};
    mongocxx::client& get_client() {
      static mongocxx::client client{mongocxx::uri{ "link*****" };};
      return client;
    }
    

    By putting this in a separate .cpp file, you ensure that inst is created some time before the main function starts. The static keyword in get_client ensures that the client is only ever created once, namely the first time get_client is called.