在linux里面安装了通过mysql :yum install mysql-server
安装完成后,在编程编译时发现找不到对应mysql.h头文件。
gcc -o mysql mysql.c
mysql.c:2:21: error: mysql.h: No such file or directory
mysql.c: In function ‘main’:
mysql.c:6: error: ‘MYSQL’ undeclared (first use in this function)
mysql.c:6: error: (Each undeclared identifier is reported only once
mysql.c:6: error: for each function it appears in.)
mysql.c:6: error: expected ‘;’ before ‘mysql’
mysql.c:8: error: ‘mysql’ undeclared (first use in this function)
此时我们只要在安装一下:yum install mysql-devel 就可以在usr/include/mysql里面找到mysql.h文件了,
继续编译mysql 程序时出现如下错误:
zdg@localhost myproject]$ gcc -o mysql mysql.c -I /usr/include/mysql/
/tmp/cc5glykp.o: In function `main':
mysql.c:(.text+0x23): undefined reference to `mysql_init'
mysql.c:(.text+0x37): undefined reference to `mysql_error'
mysql.c:(.text+0x94): undefined reference to `mysql_real_connect'
mysql.c:(.text+0xa8): undefined reference to `mysql_error'
mysql.c:(.text+0xe0): undefined reference to `mysql_close'
collect2: ld returned 1 exit status
没有指定mysql 编译需要链接到的库文件,可以使用如下命令查看对应mysql 配置路径:
mysql_config
[zdg@localhost myproject]$
[zdg@localhost myproject]$ mysql_config
Usage: /usr/lib64/mysql/mysql_config [OPTIONS]
Options:
--cflags [-I/usr/include/mysql -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing -fwrapv -fPIC -DUNIV_LINUX -DUNIV_LINUX]
--include [-I/usr/include/mysql]
--libs [-rdynamic -L/usr/lib64/mysql -lmysqlclient -lz -lcrypt -lnsl -lm -lssl -lcrypto]
--libs_r [-rdynamic -L/usr/lib64/mysql -lmysqlclient_r -lz -lpthread -lcrypt -lnsl -lm -lpthread -lssl -lcrypto]
--plugindir [/usr/lib64/mysql/plugin]
--socket [/var/lib/mysql/mysql.sock]
--port [0]
--version [5.1.73]
--libmysqld-libs [-rdynamic -L/usr/lib64/mysql -lmysqld -ldl -lz -lpthread -lcrypt -lnsl -lm -lpthread -lrt -lssl -lcrypto]
[zdg@localhost myproject]$
接下来编译时指定mysql 对应头文件和库文件即可:
gcc -o mysql mysql.c -I /usr/include/mysql/ -L /usr/lib64/mysql/ -lmysqlclient
编译成功,附上测试源码:
#include <stdio.h>
#include <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",
"root",
"12345",
"db_users",
0,
NULL,
0)) {
printf("mysql_real_connect(): %s\n", mysql_error(&mysql));
return -1;
}
printf("Connected MySQL successful! \n");
mysql_close(&mysql);
return 0;
}