ubuntu上在使用c/c++连接mysql时,出现undefined reference错误解决办法

15 篇文章 0 订阅
3 篇文章 0 订阅

写了个小程序打算连一下mysql但是编译时候出现了undefined reference的问题,如下:

make
g++ -lmysqlclient -I/usr/include/mysql/ -L/usr/lib/mysql insert_DB.cpp -o run
/tmp/ccmLznHr.o: In function `main':
insert_DB.cpp:(.text+0x20): undefined reference to `mysql_init'
insert_DB.cpp:(.text+0x4b): undefined reference to `mysql_real_connect'
insert_DB.cpp:(.text+0x62): undefined reference to `mysql_error'
insert_DB.cpp:(.text+0xd7): undefined reference to `mysql_query'
insert_DB.cpp:(.text+0xe3): undefined reference to `mysql_close'
collect2: error: ld returned 1 exit status
Makefile:2: recipe for target 'all' failed
make: *** [all] Error 1

在遇到这个错误的时候就google了一下,有各种各样的说法,例如

1、出现该错误的原因是因为编译器找不到mysql_init,mysql_close等的具体实现.虽然我们包括了正确的头文件,但是 我们在编译的时候还是要连接确定的库.对于一些常用的函数的实现,gcc编译器会自动去连接一些常用库,这样我们就没有必要自己去指定了,如:printf函数.在本程序中要通过-L选项包含库文件的路径:
gcc -o conn conn.c -L /usr/local/mysql/lib/*.a -lz(http://www.cnblogs.com/rooney/archive/2013/04/06/3003138.html)

2、$ gcc -o mysqlapi $(mysql_config --cflags) mysql-c-api.c $(mysql_config --libs)

 (http://lyxxiang.blog.163.com/blog/static/22846192011615105821150/)

3、还有这样说的,要使用shell里边包含执行命令的波浪号那个点把命令包起来的,也不行

gikor@gk:~/Projects/Test/c++/database/test$ g++ `mysql_config --cflags --libs` insert_DB.cpp -o run
/tmp/ccXJfEAa.o: In function `main':
insert_DB.cpp:(.text+0x20): undefined reference to `mysql_init'
insert_DB.cpp:(.text+0x4b): undefined reference to `mysql_real_connect'
insert_DB.cpp:(.text+0x62): undefined reference to `mysql_error'
insert_DB.cpp:(.text+0xd7): undefined reference to `mysql_query'
insert_DB.cpp:(.text+0xe3): undefined reference to `mysql_close'
collect2: error: ld returned 1 exit status

还有很多说法,我一一试了一遍都不能解决这个问题,还是出现引用未定义的错误。后来仔细想了一下我装mysql的步骤时候,发现我只装了mysql-server竟然没有装mysql-client!WTF!

执行:sudo apt install mysql-client

然后再编译:


成功!

另外在之前还出现了找不到头文件的问题:

insert_DB.cpp:9:24: fatal error: mysql/mysql.h: No such file or directory compilation terminated.

这个是以为没有安装完全mysql安装包,sudo apt install libmysql++-dev ,在编译的时候加上-lmysqlclient (小写的l(L))。


  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值