为了使用 MySQL C API, 得安装软件包 libmysqlclient-dev

$ sudo apt-get install libmysqlclient-dev

在我 64 位 Ubuntu 15.10 上,libmysqlclient.a 安装的位置是:/usr/lib/x86_64-linux-gnu/

至于编译链接选项,可以借助 mysql_config 脚本来完成。

$ mysql_config --cflags
-I/usr/include/mysql -DBIG_JOINS=1  -fno-strict-aliasing   -g -fabi-version=2 -fno-omit-frame-pointer -fno-strict-aliasing
$ mysql_config --libs
-L/usr/lib/x86_64-linux-gnu -lmysqlclient -lpthread -lz -lm -ldl

写一个最简单的程序:

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

int main() {
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;

    char *server = "localhost";
    char *user = "root";
    char *password = "******";
    char *database = "test";

    conn = mysql_init(NULL);

    /* Connect to database */
    if (!mysql_real_connect(conn, server,
        user, password, database, 0, NULL, 0)) {
    fprintf(stderr, "%s\n", mysql_error(conn));
    exit(1);
    }

    /* send SQL query */
    if (mysql_query(conn, "show tables")) {
    fprintf(stderr, "%s\n", mysql_error(conn));
    exit(1);
    }

    res = mysql_use_result(conn);

    /* output table name */
    printf("MySQL Tables in mysql database:\n");
    while ((row = mysql_fetch_row(res)) != NULL)
    printf("%s \n", row[0]);

    /* close connection */
    mysql_free_result(res);
    mysql_close(conn);

    return 0;
}

编译:

$ gcc -c `mysql_config --cflags` test.c

链接:

$ gcc -o test test.o `mysql_config --libs`

MySQL 文档说:

On Unix, linking uses dynamic libraries by default.
在 Unix 上,链接默认使用动态库。

使用 ldd 命令查看 test 程序依赖的动态库:

$ ldd test
    linux-vdso.so.1 =>  (0x00007ffecd1ab000)
    libmysqlclient.so.18 => /usr/lib/x86_64-linux-gnu/libmysqlclient.so.18 (0x00007fe471310000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fe470f46000)
    libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007fe470d2b000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fe470b27000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fe470909000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fe470586000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fe47027e000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fe470067000)
    /lib64/ld-linux-x86-64.so.2 (0x0000556c5bc33000)

可以看到 test 程序依赖动态库 libmysqlclient.so

如果要改链接静态库,需添加静态库的路径名到链接命令中:

add its path name to the link command.

$ gcc -o test test.o `mysql_config --variable=pkglibdir`/libmysqlclient.a

但是问题是,光指定 libmysqlclient.a 还不够,其它库也得指定。MySQL 文档是这么说的:

mysql_config does not currently provide a way to list all libraries needed for static linking, so it might be necessary to name additional libraries on the link command (for example, -lnsl -lsocket on Solaris). To get an idea which libraries to add, use mysql_config --libs and ldd libmysqlclient.so (or otool -L libmysqlclient.dylib on OS X).

可见比较麻烦,所以就按照默认的行为来吧。


adam1q84
1.7k 声望244 粉丝

GitHub 首页:[链接]