关于Linux.so文件不能link到main.cpp文件
About Linux .so file can't link to the main.cpp file
我想创建一个.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,但没有用。
您正在将共享库编译为 C 文件(特别是 hello()
函数),但您在编译 C++ 源代码时链接了它。您需要确保可以从 C++ 可执行文件调用(即不是 name mangled)hello()
。
即添加 extern "C"
在你的 header aa.h
:
#ifdef __cplusplus
extern "C" {
#endif
void hello();
#ifdef __cplusplus
}
#endif
我建议也添加一个 include guard。
或者,如果您将 main.cpp
重命名为 main.c
,则没有它也可以正常编译。
我想创建一个.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,但没有用。
您正在将共享库编译为 C 文件(特别是 hello()
函数),但您在编译 C++ 源代码时链接了它。您需要确保可以从 C++ 可执行文件调用(即不是 name mangled)hello()
。
即添加 extern "C"
在你的 header aa.h
:
#ifdef __cplusplus
extern "C" {
#endif
void hello();
#ifdef __cplusplus
}
#endif
我建议也添加一个 include guard。
或者,如果您将 main.cpp
重命名为 main.c
,则没有它也可以正常编译。