Undefined reference to `mysql_init'

2019-01-23 17:41发布

问题:

I am trying to compile my program on my new server, but it's not working for me at the moment.

Error log is:

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

As you can see I am compiling against MySQL - I have checked that mysql.h is present in include paths.

What am I missing?

cpulogger.cpp has #include "cpulogger.h" at the top, then cpulogger.h has this:

#include <iostream>
#include <fstream>
#include <mysql/mysql.h>

The compiler does not complain about missing mysql/mysql.h, so that part must work?

Output of mysql_config:

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

Makefile:

all:
    g++ `mysql_config --cflags --libs` main.cpp logger.cpp cpulogger.cpp -o test


test: all
    ./test

It's a fresh Ubuntu server installation with a mysql-server install on it.

[solved]:

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.

回答1:

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.



标签: c++ c linker