C++ 为什么 g++ 不与我创建的动态库链接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2001141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why doesn't g++ link with the dynamic library I create?
提问by lazlow
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 :)
我想我遗漏了一些非常明显的东西,请帮助我:)
回答by Chris Dodd
-lfoo
looks for a library called libfoo.a
(static) or libfoo.so
(shared) in the current library path, so to create the library, you need to use g++ -shared -fPIC FileSystem.cpp -o libThinFS.so
-lfoo
在当前库路径中查找名为libfoo.a
(静态)或libfoo.so
(共享)的库,因此要创建该库,您需要使用g++ -shared -fPIC FileSystem.cpp -o libThinFS.so
回答by jernkuan
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"
使用“冒号”将按原样使用库名称,而不需要前缀“lib”
回答by jernkuan
the name of the output file should be libThinFS.so, e.g.
输出文件的名称应该是libThinFS.so,例如
g++ -shared -fPIC FileSystem.cpp -o libThinFS.so
回答by Luká? Lalinsky
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.
的结果g++ -shared -fPIC FileSystem.cpp
不是目标文件,因此不应以.o
. 此外,共享库应命名为libXXX.so
. 重命名库,它将起作用。
回答by Hardy
Check out this article.
看看这篇文章。
http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html
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.
关于如何构建不同类型库的好资源。它还描述了如何以及在何处使用它们。