我想以this为基础帖子,因为我的症状是相同的,但解决方案似乎是其他东西。
我正在 Ubuntu 容器 (Ubuntu 16.04.3 LTS) 中工作,尝试编译一个最终将连接到 SQL 服务器的玩具 C 程序。首先,我安装了最新的 libmysqlclient-dev:
root@1234:/home# apt install libmysqlclient-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
libmysqlclient-dev is already the newest version (5.7.24-0ubuntu0.16.04.1).
0 upgraded, 0 newly installed, 0 to remove and 88 not upgraded.
root@1234:/home#
当我查看/usr/include/mysql 目录时,我看到了我需要的关键头文件:
root@1234:/home# ls -l /usr/include/mysql | grep mysql.h
-rw-r--r-- 1 root root 29207 Oct 4 05:48 /usr/include/mysql/mysql.h
root@1234:/home#
到目前为止,一切都很好。现在我从here找到了这个小玩具程序:
#include <stdio.h>
#include "/usr/include/mysql/mysql.h"
int main() {
MYSQL mysql;
if(mysql_init(&mysql)==NULL) {
printf("\nInitialization error\n");
return 0;
}
mysql_real_connect(&mysql,"localhost","user","pass","dbname",0,NULL,0);
printf("Client version: %s",mysql_get_client_info());
printf("\nServer version: %s",mysql_get_server_info(&mysql));
mysql_close(&mysql);
return 1;
}
现在,按照上一篇文章的建议,我使用“-I”选项进行编译以指向 mysql.h 头文件。 (是的,我在这里需要使用GCC):
root@1234:/home# gcc -I/usr/include/mysql sqlToy.c
/tmp/cc8c5JmT.o: In function `main':
sqlToy.c:(.text+0x25): undefined reference to `mysql_init'
sqlToy.c:(.text+0x69): undefined reference to `mysql_real_connect'
sqlToy.c:(.text+0x72): undefined reference to `mysql_get_client_info'
sqlToy.c:(.text+0x93): undefined reference to `mysql_get_server_info'
sqlToy.c:(.text+0xb4): undefined reference to `mysql_close'
collect2: error: ld returned 1 exit status
root@1234:/home#
肚子翻了!编译器不知道所有 mySQL 函数是什么,尽管我已尽我所能想到指向该头文件。作为健全性检查,我确保这些 mySQL 函数确实位于该头文件中;这是一个例子:
root@1234:/home# more /usr/include/mysql/mysql.h | grep mysql_init
libmysqlclient (exactly, mysql_server_init() is called by mysql_init() so
MYSQL * STDCALL mysql_init(MYSQL *mysql);
root@1234:/home#
因此,虽然我已将编译器指向我的代码中的 mysql.h 头文件并使用“-I”选项,但它仍然不知道这些“mysql”函数是什么。 “-I”选项是上一篇文章中的解决方案,但在这里对我不起作用。
那么...可能是什么问题?我假设这不是编译问题,但也许是链接问题?换句话说,我向GCC展示了mysql.h文件在哪里,但他在处理代码时仍然没有使用它?
最佳答案
header 不是库。您在编译期间包含了 MySQL header ,因此定义了这些函数,但您没有链接到实际提供这些函数的库。
这些函数由libmysqlclient
库提供,因此您需要将-lmysqlclient
标志添加到命令行来修复此问题。 (请注意,这是小写的 l
,而不是 I
。)
此外,由于您要将 /usr/include/mysql
添加到系统 header 路径中,因此可以将该库包含为
#include <mysql.h>
您不需要——也不应该! -- 在 #include
指令中指定库的完整路径。
关于mysql - 使用gcc的C代码无法链接到mysql头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53267923/