Вопрос

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'
Это было полезно?

Решение

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.

Другие советы

If your library make references to sqlite3, you should link sqlite after linking your library :

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

Otherwise ld won't find anything useful in libsqlite3 before linking your library and won't be able to find the requested symbols after that.

Since your library uses sqlite3, you need to add that AFTER your own library in the linker command. I think you could add it to the linking of your shared library too, but not certain.

The linker resolves libraries and their references in the order you list them, so the order is important.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top