首先是问题:
代码如下
[root@petrichor test]# more test2.c
#include <stdio.h>
#include <mysql/mysql.h>
int main(int argc, const char *argv[])
{
MYSQL mysql;
if (NULL == mysql_init(&mysql)) { //分配和初始化MYSQL对象
printf("mysql_init(): %s\n", mysql_error(&mysql));
return -1;
}
//尝试与运行在主机上的MySQL数据库引擎建立连接
if (NULL == mysql_real_connect(&mysql,
"localhost",//host
"root", //user
"双引号内是密码", //passward
"test", //database
0, //port
NULL, //unix_socket
0)) { //client_flag
printf("mysql_real_connect(): %s\n", mysql_error(&mysql));
return -1;
}
printf("Connected MySQL successful! \n");
mysql_close(&mysql);
return 0;
}
代码里用了几个函数像mysql_init()等等
直接编译如下
[root@petrichor test]# gcc -o test2 test2.c
/tmp/ccRafFJG.o: In function `main':
test2.c:(.text+0x23): undefined reference to `mysql_init'
test2.c:(.text+0x37): undefined reference to `mysql_error'
test2.c:(.text+0x7e): undefined reference to `mysql_real_connect'
test2.c:(.text+0x96): undefined reference to `mysql_error'
test2.c:(.text+0xc8): undefined reference to `mysql_close'
collect2: error: ld returned 1 exit status
接着是多数的解决方案,即加上-lmysqlclient
但是我解决不了
[root@petrichor test]# gcc -o test2 test2.c -lmysqlclient
/usr/bin/ld: cannot find -lmysqlclient
collect2: error: ld returned 1 exit status
使用mysql_config
命令查看编译选项
[root@petrichor test]# mysql_config
Usage: /usr/bin/mysql_config-64 [OPTIONS]
Compiler: GNU 8.3.1
Options:
--cflags [-I/usr/include/mysql -m64 ]
--cxxflags [-I/usr/include/mysql -m64 ]
--include [-I/usr/include/mysql]
--libs [-L/usr/lib64/mysql -lmysqlclient -lpthread -lz -lm -lrt -lssl -lcrypto -ldl]
--libs_r [-L/usr/lib64/mysql -lmysqlclient -lpthread -lz -lm -lrt -lssl -lcrypto -ldl]
--plugindir [/usr/lib64/mysql/plugin]
--socket [/var/lib/mysql/mysql.sock]
--port [0]
--version [8.0.21]
--variable=VAR VAR is one of:
pkgincludedir [/usr/include/mysql]
pkglibdir [/usr/lib64/mysql]
plugindir [/usr/lib64/mysql/plugin]
使用--libs
对应的进行编译(本文解决办法)
[root@petrichor test]# gcc -o test2 test2.c -L/usr/lib64/mysql -lmysqlclient -lpthread -lz -lm -lrt -lssl -lcrypto -ldl
[root@petrichor test]# ls
test1.c test2 test2.c
[root@petrichor test]# ./test2
Connected MySQL successful!
[root@petrichor test]#
总结:还是对gcc命令一知半解~