如何使用CMake和-L编译C++/usr/include/mariadb/mysql -lmariadbclient

p1tboqfb  于 2022-11-08  发布在  Mysql
关注(0)|答案(2)|浏览(152)

我的C++文件包括如下的mariadb/mysql.h。


# include <mariadb/mysql.h>

我编译我的C++文件如下。

g++ -std=c++2a -g main.cpp -o main -lmariadbclient

它工作正常。但是如果我想使用CMakeLists.txt编译我的C文件。如何使用CMake编译带有-lmariadbclient的C源代码?

jjhzyzn0

jjhzyzn01#

它看起来像主要发行版船与一个pkg-config文件为mariadb所谓的“mysqlclient.pc”。
因此您可以执行:

find_package(FindPkgConfig REQUIRED)
pkg_check_modules(mariadb REQUIRED IMPORTED_TARGET "mysqlclient")

然后将其链接到您程序,如下所示:

target_link_libraries(my_program PUBLIC PkgConfig::mariadb)
2sbarzqh

2sbarzqh2#

在主CMakeLists.txt中添加以下内容。

list(INSERT CMAKE_MODULE_PATH 0 "${CMAKE_CURRENT_SOURCE_DIR}/cmake-modules")

find_package(MariaDBClient REQUIRED)

target_link_libraries(
    your_project_name
    MariaDBClient::MariaDBClient
)

在与主CMakeLists.txt相同的目录中,创建目录cmake-modules,并在cmake-modules目录中创建文件FindMariaDBClient.cmake
FindMariaDBClient.cmake文件中添加以下内容。

find_path(MariaDBClient_INCLUDE_DIR NAMES mysql.h PATH_SUFFIXES mariadb mysql)

set(BAK_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
set(CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_SHARED_LIBRARY_SUFFIX})
find_library(MariaDBClient_LIBRARY
    NAMES mariadb libmariadb mariadbclient libmariadbclient mysqlclient 
    libmysqlclient
    PATH_SUFFIXES mariadb mysql
)
set(CMAKE_FIND_LIBRARY_SUFFIXES ${BAK_CMAKE_FIND_LIBRARY_SUFFIXES})

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(MariaDBClient DEFAULT_MSG 
MariaDBClient_LIBRARY MariaDBClient_INCLUDE_DIR)

if(MariaDBClient_FOUND)
    if(NOT TARGET MariaDBClient::MariaDBClient)
        add_library(MariaDBClient::MariaDBClient UNKNOWN IMPORTED)
        set_target_properties(MariaDBClient::MariaDBClient PROPERTIES
            INTERFACE_INCLUDE_DIRECTORIES "${MariaDBClient_INCLUDE_DIR}"
            IMPORTED_LOCATION "${MariaDBClient_LIBRARY}")
    endif()
endif()

mark_as_advanced(MariaDBClient_INCLUDE_DIR MariaDBClient_LIBRARY)

set(MariaDBClient_LIBRARIES ${MariaDBClient_LIBRARY})
set(MariaDBClient_INCLUDE_DIRS ${MariaDBClient_INCLUDE_DIR})

相关问题