未定义的对 `mysql_init' 的引用
我正在尝试在我的新服务器上编译我的程序,但目前它不适合我.
I am trying to compile my program on my new server, but it's not working for me at the moment.
错误日志是:
rasmus@web01:~/c++$ make test
g++ `mysql_config --cflags --libs` main.cpp logger.cpp cpulogger.cpp -o test
/tmp/ccPaMZUy.o: In function `CPULogger':
/home/rasmus/c++/cpulogger.cpp:7: undefined reference to `mysql_init'
/home/rasmus/c++/cpulogger.cpp:8: undefined reference to `mysql_real_connect'
/home/rasmus/c++/cpulogger.cpp:10: undefined reference to `mysql_get_client_info'
/tmp/ccPaMZUy.o: In function `~CPULogger':
/home/rasmus/c++/cpulogger.cpp:16: undefined reference to `mysql_close'
collect2: ld returned 1 exit status
make: *** [all] Error 1
如您所见,我正在针对 MySQL 进行编译 - 我已检查 mysql.h 是否存在于包含路径中.
As you can see I am compiling against MySQL - I have checked that mysql.h is present in include paths.
我错过了什么?
cpulogger.cpp 在顶部有 #include "cpulogger.h",然后 cpulogger.h 有这个:
cpulogger.cpp has #include "cpulogger.h" at the top, then cpulogger.h has this:
#include <iostream>
#include <fstream>
#include <mysql/mysql.h>
编译器不会抱怨缺少mysql/mysql.h,所以那部分一定可以工作吗?
The compiler does not complain about missing mysql/mysql.h, so that part must work?
rasmus@web01:~/c++$ mysql_config --cflags --libs
-I/usr/include/mysql -DBIG_JOINS=1 -fno-strict-aliasing -g
-L/usr/lib -lmysqlclient -lpthread -lz -lm -lrt -ldl
生成文件:
all:
g++ `mysql_config --cflags --libs` main.cpp logger.cpp cpulogger.cpp -o test
test: all
./test
这是一个全新的 Ubuntu 服务器安装,上面安装了 mysql-server.
It's a fresh Ubuntu server installation with a mysql-server install on it.
[已解决]:
将链接器库放在编译器命令的末尾是可行的.
Putting linker libraries at the end of the compiler commands works.
all:
g++ main.cpp logger.cpp cpulogger.cpp -o test `mysql_config --cflags --libs`
请参阅下面的答案以获得解释.
See answer below for explanation.
推荐答案
链接器的参数顺序很重要.使用 mysql-config after 列出需要它的文件.链接器将看到 cpulogger.o 需要 mysql_init 并在其后列出的库中查找符号.如果这些库在参数中较早列出,则不会再次搜索它们.
The order of arguments to the linker is significant. Use mysql-config after listing the files that need it. The linker will see that cpulogger.o needs mysql_init and look in libraries listed after it for the symbol. If the libraries were listed earlier in the arguments they won't be searched again.
相关文章