“文档” 菜单
文档首页
/ / /
C 驱动程序
/ /

在 C 程序中使用 libbson

在此页面上

  • 包含 bson.h
  • CMake
  • pkg-config

libbson 的所有函数和类型都在一个头文件中可用。只需包含 bson.h即可:

hello_bson.c
#include <stdio.h>
#include <bson/bson.h>
int
main (int argc, const char **argv)
{
bson_t *b;
char *j;
b = BCON_NEW ("hello", BCON_UTF8 ("bson!"));
j = bson_as_canonical_extended_json (b, NULL);
printf ("%s\n", j);
bson_free (j);
bson_destroy (b);
return 0;
}

libbson 安装包括 CMake 配置文件包 ,这样您就可以使用 CMake 的 find_package 命令导入 libbson 的 CMake 目标并链接到 libbson(作为共享库):

CMakeLists.txt
# Specify the minimum version you require.
find_package (bson-1.0 1.7 REQUIRED)
# The "hello_bson.c" sample program is shared among four tests.
add_executable (hello_bson ../../hello_bson.c)
target_link_libraries (hello_bson PRIVATE mongo::bson_shared)

您也可以使用 libbson 作为静态库:使用mongo::bson_static CMake 目标:

# Specify the minimum version you require.
find_package (bson-1.0 1.7 REQUIRED)
# The "hello_bson.c" sample program is shared among four tests.
add_executable (hello_bson ../../hello_bson.c)
target_link_libraries (hello_bson PRIVATE mongo::bson_static)

如果您不使用 CMake,请使用 pkg-config 在命令行中设置标头和库路径:

gcc -o hello_bson hello_bson.c $(pkg-config --libs --cflags libbson-1.0)

或者静态链接到 libbson:

gcc -o hello_bson hello_bson.c $(pkg-config --libs --cflags libbson-static-1.0)

后退

教程

来年

创建 BSON 文档