Link error with my own C++ library

你离开我真会死。 提交于 2019-12-11 07:17:24

问题


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'

回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/16084847/link-error-with-my-own-c-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!