Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined reference to `mysql_init'

Tags:

c++

c

linker

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.

like image 274
Rasmus Styrk Avatar asked Jun 10 '12 16:06

Rasmus Styrk


1 Answers

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.

like image 85
Jonathan Wakely Avatar answered Sep 18 '22 14:09

Jonathan Wakely