Add and link mysql libraries in a cmakelist.txt

2019-01-20 06:42发布

问题:

I'm working in a project where I need to use MySQL LIBRARIES. I had success in the past, using a simple makefile where I wrote the specific flags.

CFLAGS+=`mysql_config --cflags`
LIB+=`mysql_config --libs`

However... for my project is required to use a cmakelist and I'm having difficulties with that. I can add GTK libraries with this code:

find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED gtk+-3.0)

include_directories(${GTK_INCLUDE_DIRS})
link_directories(${GTK_LIBRARY_DIRS})
target_link_libraries( cgm ${GTK_LIBRARIES} )

but for MySQL I'm in trouble. I tried many things unsuccessfully, but I believe that is similar to the GTK example. Can anyone help me with this problem?

回答1:

The simplest way could be to find (e.g. with google) FindMySQL.cmake script, which works for you. This script can be used with find_package command as usual:

list(CMAKE_MODULE_PATH APPEND <directory-where-FindMySQL.cmake-exists>)
find_package(MySQL REQUIRED)

include_directories(${MYSQL_INCLUDE_DIR})
target_link_libraries(cgm ${MYSQL_LIB})

(Names of variables MYSQL_INCLUDE_DIR and MYSQL_LIB can be different for concrete script).

But it is not difficult to link with MySQL library manually, knowing way for compute CFLAGS and LIBS.

During configuration stage(executing of cmake) programs can be run with execute_process, for add CFLAGS and LIBS for specific target use target_compile_options and target_link_libraries correspondingly :

execute_process(COMMAND mysql_config --cflags
    OUTPUT_VARIABLE MYSQL_CFLAGS OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process(COMMAND mysql_config --libs
    OUTPUT_VARIABLE MYSQL_LIBS OUTPUT_STRIP_TRAILING_WHITESPACE)

target_compile_options(cgm PUBLIC ${MYSQL_CFLAGS})
target_link_libraries(cgm ${MYSQL_LIBS})