【问题标题】:Why doesn't g++ link with the dynamic library I create?为什么 g++ 不与我创建的动态库链接?
【发布时间】:2011-01-01 08:23:47
【问题描述】:

我一直在尝试制作一些都依赖同一个库的应用程序,动态库是我的第一个想法:所以我开始编写“库”:

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

我认为我遗漏了一些非常明显的东西,请帮助我:)

【问题讨论】:

    标签: c++ g++ dynamic-linking ld


    【解决方案1】:

    输出文件的名称应该是libThinFS.so,例如

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

    【讨论】:

      【解决方案2】:

      g++ -shared -fPIC FileSystem.cpp 的结果不是目标文件,因此不应以.o 结尾。此外,共享库应命名为libXXX.so。重命名库,它就会工作。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 谢谢,前面缺少 lib(.o 而不是 .so 只是一个错字):)
        【解决方案4】:

        看看这篇文章。

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

        关于如何构建不同类型库的好资源。它还描述了如何以及在何处使用它们。

        【讨论】:

          【解决方案5】:

          你可以使用

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

          使用“冒号”将按原样使用库名称,而不是需要前缀“lib”

          【讨论】:

            猜你喜欢
            • 2010-10-04
            • 1970-01-01
            • 1970-01-01
            • 2014-04-18
            • 2011-09-05
            • 1970-01-01
            • 2021-02-17
            • 1970-01-01
            相关资源
            最近更新 更多