简体   繁体   中英

Why doesn't g++ link with the dynamic library I create?

I've been trying to make some applications which all rely on the same library, and dynamic libraries were my first thought: So I began writing the "Library":

/* ThinFS.h */

class FileSystem {
public:
    static void create_container(string file_name); //Creates a new container 
};

/* ThinFS.cpp */
#include "ThinFS.h"
void FileSystem::create_container(string file_name) {
     cout<<"Seems like I am going to create a new file called "<<file_name.c_str()<<endl;
}

I then compile the "Library"

g++ -shared -fPIC FileSystem.cpp -o ThinFS.o

I then quickly wrote a file that uses the Library:

#include "ThinFS.h"
int main() {
    FileSystem::create_container("foo");
    return (42);
}

I then tried to compile that with

g++ main.cpp -L. -lThinFS

But it won't compile with the following error:

/usr/bin/ld: cannot find -lThinFS
collect2: ld returned 1 exit status

I think I'm missing something very obvious, please help me :)

-lfoo在当前库路径中查找名为libfoo.a (static)或libfoo.so (shared)的库,因此要创建库,需要使用g++ -shared -fPIC FileSystem.cpp -o libThinFS.so

You can use

g++ main.cpp -L. -l:ThinFS 

The use of "colon" will use the library name as it is, rather requiring a prefix of "lib"

the name of the output file should be libThinFS.so , eg

g++ -shared -fPIC FileSystem.cpp -o ThinFS.

The result of g++ -shared -fPIC FileSystem.cpp is not an object file, so it should not end with .o . Also, shared libraries should be named libXXX.so . Rename the library and it will work.

Check out this article.

http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html

A good resource on how to build different types of libraries. It also describes how and where to use them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM