使用gcc的c代码不能链接到mysql头?

wmvff8tz  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(270)

我想在这篇文章的基础上,因为我的症状是相同的,但解决办法似乎是别的。
我正在一个ubuntu容器(ubuntu16.04.3lts)中工作,试图编译一个toyc程序,它最终将连接到一个sql服务器。首先:我安装了最新的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#

到目前为止,还不错。现在我从这里找到了这个小玩具程序:


# 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#

因此,虽然我已经在代码中以及使用“-i”选项将编译器指向mysql.h头文件,但它仍然不知道那些“mysql”函数是什么。“-i”选项是前一篇文章中的解决方案,但在这里不适用于我。
所以。。。有什么问题吗?我假设这不是编译问题,但可能是链接问题?换句话说,我向gcc展示了mysql.h文件的位置,但他在处理代码时仍然没有使用它?

vbkedwbf

vbkedwbf1#

头不是库。在编译过程中包含mysql头,因此定义了这些函数,但是没有针对实际提供这些函数的库进行链接。
这些功能由 libmysqlclient 库,所以需要添加 -lmysqlclient 标记到命令行以修复此问题(请注意,这是小写 l ,不是 I .)
此外,由于您正在添加 /usr/include/mysql 在系统头路径中,可以将库包含为


# include <mysql.h>

你不需要也不应该在中指定库的完整路径 #include 指令。

相关问题