- libbson 1.13.1 »
- Tutorial

# Using libbson In Your C Program

## Include bson.h

All libbson’s functions and types are available in one header file. Simply include `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;
    }

## CMake

The libbson installation includes a CMake config-file package, so you can use CMake’s find_package command to find libbson’s header and library paths and link to libbson:

CMakeLists.txt

    # Specify the minimum version you require.
    find_package (libbson-1.0 1.7 REQUIRED)

    message ("--   libbson found version \"${BSON_VERSION}\"")
    message ("--   libbson include path \"${BSON_INCLUDE_DIRS}\"")
    message ("--   libbson libraries \"${BSON_LIBRARIES}\"")

    # The "hello_bson.c" sample program is shared among four tests.
    add_executable (hello_bson ../../hello_bson.c)
    target_include_directories (hello_bson PRIVATE ${BSON_INCLUDE_DIRS})
    target_link_libraries (hello_bson PRIVATE ${BSON_LIBRARIES})
    target_compile_definitions (hello_bson PRIVATE ${BSON_DEFINITIONS})

By default, libbson is dynamically linked. You can use libbson as a static library instead: Use the included `libbson-static-1.0` config-file package and (on Unix) link to `pthread`:

    # Specify the minimum version you require.
    find_package (libbson-static-1.0 1.7 REQUIRED)

    message ("--   libbson-static found version \"${BSON_STATIC_VERSION}\"")
    message ("--   libbson-static include path \"${BSON_STATIC_INCLUDE_DIRS}\"")
    message ("--   libbson-static libraries \"${BSON_STATIC_LIBRARIES}\"")

    # The "hello_bson.c" sample program is shared among four tests.
    add_executable (hello_bson ../../hello_bson.c)
    target_include_directories (hello_bson PRIVATE ${BSON_STATIC_INCLUDE_DIRS})
    target_link_libraries (hello_bson PRIVATE ${BSON_STATIC_LIBRARIES})
    target_compile_definitions (hello_bson PRIVATE ${BSON_STATIC_DEFINITIONS})

## pkg-config

If you’re not using CMake, use pkg-config on the command line to set header and library paths:

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

Or to statically link to libbson:

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

Created using Sphinx 1.8.3, based on Sphinx Readable Theme.