MognoDb Linux C++ Driver 编译,运行注意事项

  1. MongoDb C++ Driver 一般安装于 ./usr/local目录下,在这个目录下你能看到 boost文件夹, include文件夹(内部有bsoncxx,libbson, libmongoc, mongocxx等), lib文件夹(libson,libmongoc,mongocxx的各种so文件)

  2. 我们使用VisualStuio编译Linux工程,工程文件的设置如下:

    • VC++ Directories
      Include Directories:
      c:\boost_1_60_0\;C:\mongo-cxx-driver\include\mongocxx\v_noabi;C:\mongo-cxx-driver\include\bsoncxx\v_noabi;C:\mongo-c-driver\include\libmongoc-1.0;C:\mongo-c-driver\include\libbson-1.0;$(IncludePath)
      这个设置主要是为了在Visual Studio查看代码时不会出现满天的波浪符号
    • C/C++/All Options:
      Additional Options:
      -I/usr/local/include/mongocxx/v_noabi
      -I/usr/local/include/libmongoc-1.0
      -I/usr/local/include/bsoncxx/v_noabi
      -I/usr/local/include/libbson-1.0
      C++ Language Standard: C++ 11
    • Linker/All Options:
      Additional Options:
      -L/usr/local/lib -Wl,-rpath=/usr/local/lib -lmongocxx -lbsoncxx
  3. 实例程序:

#include <chrono>
#include <iostream>
#include <thread>

#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>

using namespace std;

int main(int, char**) {
    mongocxx::instance inst{};
    mongocxx::uri uri("mongodb://localhost:27017");
    mongocxx::client conn{ uri };

    auto dbs = conn.list_databases();
    for (auto view : dbs)
    {
        auto element = view["name"];
        const std::string name = element.get_utf8().value.to_string();
        cout << name << endl;
    }
}

4.到这里运行可能会报错,找不到 mongocxx.so._noabi 等错误,这是因为我们把driver安装在./usr/local/lib目录下,需要在ld.so.conf文件中指明系统尝试去./usr/local/lib中去找需要的so文件
进入/etc文件夹, 编辑 ld.so.conf 文件(可以用vim)
在文件添加一行:
/usr/local/lib
保存完毕后,再次运行 ldconfig 生效

posted on 2022-08-29 20:10  norsd  阅读(2)  评论(0编辑  收藏  举报  来源

导航