C++ linking error

Hi everyone. I am trying to link MongoDB C++ Driver version 3.4.0-5#1 uploaded with vcpkg with g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0. I have linking error. Here is the full log of errors:

/usr/bin/ld: /opt/vcpkg/installed/x64-linux/lib/libmongoc-1.0.a(mongoc-client.c.o): in function `_mongoc_get_rr_search':
mongoc-client.c:(.text+0x1fd): undefined reference to `__res_nsearch'
/usr/bin/ld: mongoc-client.c:(.text+0x2fe): undefined reference to `ns_initparse'
/usr/bin/ld: mongoc-client.c:(.text+0x36a): undefined reference to `ns_parserr'
/usr/bin/ld: mongoc-client.c:(.text+0x42d): undefined reference to `ns_parserr'
/usr/bin/ld: /opt/vcpkg/installed/x64-linux/lib/libmongoc-1.0.a(mongoc-client.c.o): in function `srv_callback':
mongoc-client.c:(.text+0x58e): undefined reference to `__dn_expand'
collect2: error: ld returned 1 exit status

Here what I have in CMake:

find_package(libmongocxx REQUIRED)
find_package(libbsoncxx REQUIRED)
include_directories(${LIBMONGOCXX_INCLUDE_DIR})
include_directories(${LIBBSONCXX_INCLUDE_DIR})

target_link_libraries(PROJECT_NAME ${LIBMONGOCXX_LIBRARIES})
target_link_libraries(PROJECT_NAME ${LIBBSONCXX_LIBRARIES})

what could be the root cause of that?

You do not describe how your C driver and C++ driver packages are built. Or perhaps that is the meaning of “vcpkg”, though I am not familiar with that. In any event, it seems like linker does not know to link with -lresolv. The cause of this might be that you are using include_directories(${LIBBSONCXX_INCLUDE_DIR}) and target_link_libraries(PROJECT_NAME ${LIBBSONCXX_LIBRARIES}). Since you are using CMake, the recommended approach is to instead use the CMake targets that become available when the find_package() call returns. Also, libmongocxx depends on libbsoncxx, so only the former is required. You should be able to do something like this:

find_package(libmongocxx REQUIRED)

target_link_libraries(PROJECT_NAME mongo::mongocxx_shared)

Additional details can be found in the C++ driver source distribution in these files:

examples/projects/mongocxx/cmake/shared/CMakeLists.txt
examples/projects/mongocxx/cmake/static/CMakeLists.txt
1 Like

HI thanks for the info, actually I resolve the issue only by building from source.