My C file includes the mariadb/mysql.h as following.
#include <mariadb/mysql.h>
I compile my C file as following.
g -std=c 2a -g main.cpp -o main -lmariadbclient
It works fine. But if I want to compile my C file using CMakeLists.txt. How to compile the C source code with -lmariadbclient
using CMake?
CodePudding user response:
It looks like major distros ship with a pkg-config file for mariadb called "mysqlclient.pc".
So you can do:
find_package(FindPkgConfig REQUIRED)
pkg_check_modules(mariadb REQUIRED IMPORTED_TARGET "mysqlclient")
and then link it to your program like so:
target_link_libraries(my_program PUBLIC PkgConfig::mariadb)
CodePudding user response:
Add the following in the main 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
)
In the same directory as the main CMakeLists.txt
, create the directory cmake-modules
and create the file FindMariaDBClient.cmake
in the cmake-modules
directory.
Add the following in the FindMariaDBClient.cmake
file.
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})