【问题标题】:linking g++ code with shared library build with gcc使用 gcc 将 g++ 代码与共享库构建链接
【发布时间】:2011-03-10 01:58:54
【问题描述】:

我使用 gcc 制作了共享库。我想使用 g++ 编译器将这个库与源代码 *.c 链接起来。 示例

test_init.c
#include<stdio.h>
int test_init()
{
   printf(" test init success\n");
   return 0;
}

gcc -shared -o libtest.so test_init.c

test.c

#include<stdio.h>
extern int test_init();
main()
{
   test_init();
}

g++ -I. -L. -ltest test.c

/tmp/ccuH5tIO.o:在函数main': test.c:(.text+0x7): undefined reference totest_init()'collect2: ld 返回 1 个退出状态

注意:如果我用 gcc 编译 test.c 它可以工作,但由于其他依赖关系,我想使用这种方法。可以吗??

【问题讨论】:

    标签: gcc g++


    【解决方案1】:

    通过声明它们从 C++ 调用 C 例程

     extern "C" {
         ....
     }
    

    查看系统或 Google 上的一些头文件——这是唯一的方法,因为语言之间的函数签名系统不同。

    【讨论】:

    • 我试过了,但没有用。在这种情况下,两者都是 c 文件,但可执行文件是使用 g++ 编译器制作的
    【解决方案2】:

    正如德克所说,将extern int test_init(); 更改为extern "C" { int test_init(); }

    【讨论】:

      【解决方案3】:

      通常-llibrary应该在gcc命令行中的目标文件或c/c++文件之后

      g++ -I. -L. test.c -ltest
      

      链接器在处理完 test.c 后会搜索 test.c 中提到的符号,当您将 -llib 放在 test.c 之前时,它只是无法找到它们。

      请参阅man ld 了解更多信息。

      不确定您使用extern 时的情况,可能在这种情况下有所不同。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-18
        • 2010-11-03
        • 2011-04-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多