Search code examples
c++dynamic-library

Link error with my own C++ library


This is my first time trying to make a simple library. I worked in Ubuntu 12.04 with g++ 4.6.3. Here is the problem:

[[mylib.cpp]]
#include<sqlite3.h>
void Mylib::blahblah() {...}
void Mylib::evenmoreblah() {...}
...

[[mylib.h]]
#include <...>
class Mylib {
    ...
};

Then I made the lib by:

 gcc -c -Wall -fpic mylib.cpp
 gcc -shared -o libmylib.so mylib.o

I used the library in a single test.cpp which contains only the main(). I put libmylib.so in ./libdir, and compiled by using:

 g++ -g test.cpp -o test -lpthread -L/usr/local/lib -lsqlite3 -L./libdir -lmylib

The error I got:

./libdir/libmylib.so: undefined reference to `sqlite3_close'
./libdir/libmylib.so: undefined reference to `sqlite3_exec'
./libdir/libmylib.so: undefined reference to `sqlite3_free'
./libdir/libmylib.so: undefined reference to `sqlite3_open'

Solution

  • You could link -lsqlite3 into your shared library with

     gcc -shared mylib.o -o libmylib.so -lsqlite3
    

    If you do that, you don't need to explicitly link -lsqlite3 to your program, but that won't harm.

    and the order of linking arguments for your program is important:

     g++ -Wall -g test.cpp -o mytest \
       -L./libdir -lmylib -L/usr/local/lib -lsqlite3 -lpthread
    

    it should go from higher-level libraries to lower-level (i.e. system) ones. And don't forget -Wall to get almost all warnings from the compiler, which is very useful.

    Read the Program Library HowTo.

    PS. Don't call your program test which is a shell builtin (and the standard /usr/bin/test). Use some other name.