Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
C 驱动程序
/ /

在 C 程序中使用 libbson

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)

后退

Tutorials

在此页面上