在ubuntu上链接共享库mysql

时间:2013-05-07 17:38:11

标签: c++ mysql cmake shared-libraries

我一直在尝试创建一个小型测试应用程序,以开始使用CMake和链接库。 完成以下操作: - 我在Ubuntu上安装了libmysqlcppconn5库(即它现在位于/usr/lib/libmysqlcppconn5.so,只是默认安装) - 我创建了一个包含以下内容的小.cpp文件

#include <stdlib.h>
#include <iostream>
#include <mysql/mysql.h>

int main(int argc, char **argv) {
MYSQL *conn_ptr;
conn_ptr = mysql_init(NULL);
if (!conn_ptr) {
    std::cout << "mysql init failed\n";
    exit(1);
}
conn_ptr = mysql_real_connect (conn_ptr, "localhost", "root", "pw", "db", 0, NULL, 0);
if (conn_ptr) {
    std::cout << "connection success\n";
} else {
    std::cout << "connection failed\n";
}
mysql_close(conn_ptr);

我应该如何构建我的CMakeLists.txt以便它将使用此共享库?

1 个答案:

答案 0 :(得分:0)

如下:

# Find and make sure the system have the header file
find_path(MYSQL_HEADER mysql/mysql.h)
if(MYSQL_HEADER STREQUAL "MYSQL_HEADER-NOTFOUND")
    message(FATAL_ERROR "Could not find the mysql/mysql.h header file")
endif()

# Find and make sure the system have the library
find_library(MYSQL_LIBMYSQLCPPCONN5 mysqlcppconn5)
if(MYSQL_LIBMYSQLCPPCONN5 STREQUAL "MYSQL_LIBMYSQLCPPCONN5-NOTFOUND")
    message(FATAL_ERROR "Could not find the mysqlcppconn5 library")
endif()

# Link the library to the target
target_link_libraries(your_target ${MYSQL_LIBMYSQLCPPCONN5})