【问题标题】:About Linux .so file can't link to the main.cpp file [duplicate]关于 Linux .so 文件无法链接到 main.cpp 文件 [重复]
【发布时间】:2016-12-29 22:44:07
【问题描述】:

我想创建一个.so文件,让main.cpp文件可以调用.so文件中的函数。

这些是我的文件。

//aa.h
#include <stdio.h>
#include <stdlib.h>
void hello();

//hola.c
#include <stdio.h>
#include "aa.h"
void hello()
{printf("Hello world!\n");}

//main.cpp
#include "aa.h"
void hello();
int main(){hello();return 0;}

这是下面的步骤。

第 1 步:创建 .so 文件

$ gcc hola.c  -fPIC -shared -o libhola.so

有效

第 2 步:将 libhola.so 链接到 main.cpp 并创建一个名为 test 的执行文件

$ gcc main.cpp -L. -lhola -o test

我尝试过的只需两步。

而且报错说:

main.cpp:(.text+0x12): undefined reference to `hello()'
collect2: error: ld returned 1 exit status

我曾尝试将 libhola.so 移动到 /usr/lib 并将 aa.h 移动到 /usr/inclued,但不起作用。

【问题讨论】:

  • 如果我是对的,头文件应该包含#ifndef SOME_NAME #define SOME_NAME // Do something #endif
  • C++ 语言修改了所有函数名称以包括返回类型和参数类型。 C 语言不这样做。 gcc 编译器不适用于编译/链接 C++ 代码。请改用g++gpp。获取c++主程序处理库中的函数hello,库的头文件必须有#ifdef cplusplus { .... } wrapped around the prototype for the hello`函数。注意,由于hello 的原型在头文件中,所以不要在main.c 文件中重复该原型
  • 从 cmd 提示符调用 ldconfig。还要检查ldconfig -p | grep "hola" 是否给出了一些结果。

标签: c++ c linux shared-libraries


【解决方案1】:

您正在将共享库编译为 C 文件(特别是 hello() 函数),但您在编译 C++ 源代码时链接它。您需要确保可以从 C++ 可执行文件中调用 hello()(即不是 name mangled)。

即在标题中添加extern "C" aa.h:

#ifdef __cplusplus
 extern "C" {
#endif
void hello();

#ifdef __cplusplus
}
#endif

我建议也添加一个include guard

或者,如果您将main.cpp 重命名为main.c,那么没有这个也可以正常编译。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多