apt-get install cmake libssl-dev libsasl2-dev
安装编译所需要的软件 ;如果没有gcc,g++,gdb也请安装好;
wget https://github.com/mongodb/mongo-c-driver/releases/download/1.21.1/mongo-c-driver-1.21.1.tar.gz tar xzf mongo-c-driver-1.21.1.tar.gz cd mongo-c-driver-1.21.1 mkdir cmake-build cd cmake-build cmake -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF .. cmake --build . cmake --build . --target install
curl -OL https://github.com/mongodb/mongo-cxx-driver/releases/download/r3.6.6/mongo-cxx-driver-r3.6.6.tar.gz tar -xzf mongo-cxx-driver-r3.6.6.tar.gz cd mongo-cxx-driver-r3.6.6/build cmake ..??????????????????????????????? \ ??? -DCMAKE_BUILD_TYPE=Release????????? \ ??? -DCMAKE_INSTALL_PREFIX=/usr/local
cmake --build . sudo cmake --build . --target install
写一个测试文件main.cpp
#include <iostream>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
int main(int, char**) {
mongocxx::instance inst{};
//改成你自己的localhost服务器,向testdb写数据
mongocxx::client conn{mongocxx::uri("mongodb://11.21.14.11:27017")};
bsoncxx::builder::stream::document document{};
auto collection = conn["testdb"]["testcollection"];
document << "hello" << "world";
collection.insert_one(document.view());
auto cursor = collection.find({});
for (auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
}
}
编译:
c++ --std=c++11 main.cpp -o main $(pkg-config --cflags --libs libmongocxx)
生成main ldd ./main?? 查看可执行文件需要so库;如果发现.so库not found, export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/ 增加库路径;
用cmake和vscode结合:
在main.cpp同级目录建立 :????? CMakeLists.txt
文件内容如下:用于make.
cmake_minimum_required(VERSION 3.15)
project(main)
set(CMAKE_CXX_STANDARD 14)
add_executable(main main.cpp)
find_package(libmongocxx REQUIRED)
find_package(libbsoncxx REQUIRED)
include_directories(${LIBMONGOCXX_INCLUDE_DIR})
include_directories(${LIBBSONCXX_INCLUDE_DIR})
include_directories("/usr/local/include/mongocxx/v_noabi")
include_directories("/usr/local/include/bsoncxx/v_noabi")
include_directories("/usr/local/include/libmongoc-1.0")
include_directories("/usr/local/include/libbson-1.0")
include_directories("/usr/local/lib")
target_link_libraries(main ${LIBMONGOCXX_LIBRARIES})
target_link_libraries(main ${LIBBSONCXX_LIBRARIES})
然后ctrl+`打开终端 : make.
同样生成main ;?? 至此,结束;
|