首页 文章

GCC动态库构建问题

提问于
浏览
2

我是linux的新手,在使用动态库进行编译时,我收到了segmentationfault错误 .

我有两个文件

ctest1.c

void ctest1(int *i)
{ 
   *i =10;
}

ctest2.c

void ctest2(int *i)
{ 
   *i =20;
}

我已使用以下命令将这两个文件编译到名为libtest.so的共享库中

gcc -shared -W1,-soname,libtest.so.1 -o libtest.so.1.0.1 ctest1.o ctest2.o -lc

我已经编写了另一个程序prog.c,它使用了这个库导出的函数

prog.c中

#include <stdio.h>

void (*ctest1)(int*);
void (ctest2)(int*);


int main()
{
  int a;

  ctest1(&a);

  printf("%d",a);

  return 0;

}

当我使用以下命令构建可执行文件时

gcc -Wall prog.c -L . -o prog

但是当我运行生成的可执行文件时,我得到了SegmentationFault错误 .

当我用ldd检查prog的 Headers 时,它显示出来

linux-vdso.so.1 =>(0x00007f99dff000)libc.so.6 => /lib64/libc.so.6(0x0007feeaa8c1000)/lib64/ld-linux-x86-64.so.2(0x00007feeaac1c000)

有人可以说出问题所在

3 回答

  • 1

    你没有调用ctest1.c或ctest2.c . 相反,你在prog.c中创建ctest1和ctest2函数指针,你没有初始化,所以当你试图调用它时会导致分段错误 .

    您需要声明您的函数,以便prog.c可以看到它们,然后将prog.c链接到库(可能使用gcc的-l选项) .

    #include <stdio.h>
    
    extern void ctest1(int*);
    extern void ctest2(int*);
    
    
    int main()
    {
      int a;
    
      ctest1(&a);
    
      printf("%d",a);
    
      return 0;
    
    }
    

    类似的东西:

    gcc -Wall -L. -ltest prog.c -o prog
    
  • 6

    .so中的库是动态链接的 . 您需要在prog.c中使用dlopen()打开.so文件,找到符号,然后通过函数指针调用ctest1()和ctest2() .

  • -4

    在使用WhirlWind给你的信息后尝试这个(以'#'开头的行是注释;你不需要输入它们):

    # Ensure that any shared objects you use are available in the current directory.
    export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
    
    # Compile the library with a real name of "libctest.so.1.0.1"
    # and a soname of "libctest.so.1".
    gcc -shared -Wl,-soname,libctest.so.1 -o libctest.so.1.0.1 ctest1.o ctest2.o
    
    # Create a symbolic link with soname as the name that points to the library.
    # (libctest.so.1 -> libctest.so.1.0.1)
    /sbin/ldconfig -v -n .
    
    # Create a symbolic link using the "linker name" that points to the newly
    # created library.
    ln -sf libctest.so.1 libctest.so
    
    # Compile your program.
    gcc -Wall -L. prog.c -o prog -l ctest
    
    # Run your program (it won't work without setting LD_LIBRARY_PATH because
    # it won't be able to find your library).
    ./prog
    

    这对我有用 . 这似乎是很多工作,但经过一些试错案例后,我认为这几乎是常规的 .

    您可以在http://www.ibm.com/developerworks/library/l-shobj/找到更多信息 . :)

    编辑:我几乎忘了提到似乎很多教程建议使用-fPIC选项生成与位置无关的代码(不要将它与-fpic混淆,因为这会使你的结果库不那么便携) . 拥有它不会有什么坏处,但为了简单起见,我从上面的行中省略了它 .

相关问题