Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

c++ - Undefined reference to `mysql_init'

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...