2010-01-04 78 views
6

我一直試圖做一些應用,這都依賴於相同的庫,和動態庫是我的第一個想法:所以我開始寫的「庫」:爲什麼g ++沒有鏈接到我創建的動態庫?

/* 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; 
} 

我然後編譯「圖書館」

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

我然後迅速寫道,使用庫文件:

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

然後我試圖編譯與

g++ main.cpp -L. -lThinFS 

但它不會與下面的錯誤編譯:

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

我想我失去了一些東西很明顯,請幫我:)

回答

11

-lfoo尋找一個庫調用在當前庫路徑libfoo.a(靜態)或libfoo.so(共享),所以要創建庫,你需要使用g++ -shared -fPIC FileSystem.cpp -o libThinFS.so

+0

感謝前綴的lib在前面失蹤( .o而不是.so只是一個錯字):) – lazlow 2010-01-04 18:41:03

3

輸出文件的名稱應該是libThinFS.so,例如

 
g++ -shared -fPIC FileSystem.cpp -o libThinFS.so 
1

g++ -shared -fPIC FileSystem.cpp的結果是不是一個對象文件,所以它不應該與.o結束。此外,共享庫應命名爲libXXX.so。重命名該庫,它將工作。

6

您可以使用

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

使用「冒號」將使用這個庫的名字,因爲它是,而是需要的「LIB」

相關問題