Michał Szydłowski Michał Szydłowski - 4 months ago 8
MySQL Question

How to create a shared object library (*.so) with mysql connector?

I have written a very simple application in C, for which I would like to have a connection with MySQL database. Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <mysql.h>
#include <my_global.h>

void runtime_tile_opt(void);

int main(void) {
return 0;

void runtime_tile_opt() {
printf("MySQL client version: %s\n", mysql_get_client_info());


If i run
gcc -o runtime $(mysql_config --cflags) runtime.c $(mysql_config --libs)
, everything works fine, all libraries seemed to be properly linked, and if I run the executable, I get a legitimate-looking output:

MySQL client version: 5.5.49

However, I would like to make a shared library out of it. So I'm trying to create an object file, with

gcc -c -fPIC runtime.c $(mysql_config --cflags) -o runtime.o $(mysql_config --libs)

The outputs of
mysql_config --libs
mysql_config --cflags

-L/usr/lib/x86_64-linux-gnu -lmysqlclient -lpthread -lz -lm -ldl
-I/usr/include/mysql -DBIG_JOINS=1 -fno-strict-aliasing -g -DNDEBUG

Finally, I create my

gcc runtime.o -shared -o runtime.so

All of the above went with no errors whatsoever. However, some library is not linked apparently, since when I run a file with this plugin loaded, I get:

/home/michal/thesis/Drafts/runtime/runtime.so: undefined reference to `mysql_get_client_info'

This function is defined in the header files I included. I'm not very experienced with gcc, but I look at it and it looks as though I linked what I had to link. Any ideas where did I fail?


You still need to pass the correct -l flags to the compiler when creating a shared library. They should be the same flags you pass when creating a binary, i.e.

gcc -shared -o runtime.so $(mysql_config --cflags) runtime.o $(mysql_config --libs)

Note that the order of options is important! First pass all options, then all files and lastly libraries (-l... operands).