爲了使用 MySQL C API, 得安裝軟件包 libmysqlclient-dev
。mysql
$ sudo apt-get install libmysqlclient-dev
linux
在我 64 位 Ubuntu 15.10 上,libmysqlclient.a
安裝的位置是:/usr/lib/x86_64-linux-gnu/
。c++
至於編譯連接選項,能夠藉助 mysql_config
腳原本完成。sql
$ 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
寫一個最簡單的程序:socket
#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; }
編譯:ide
$ gcc -c `mysql_config --cflags` test.c
連接:fetch
$ gcc -o test test.o `mysql_config --libs`
MySQL 文檔說:idea
On Unix, linking uses dynamic libraries by default.
在 Unix 上,連接默認使用動態庫。code
使用 ldd
命令查看 test
程序依賴的動態庫:server
$ 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).
可見比較麻煩,因此就按照默認的行爲來吧。