【发布时间】: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 thehello`函数。注意,由于hello的原型在头文件中,所以不要在main.c文件中重复该原型 -
从 cmd 提示符调用
ldconfig。还要检查ldconfig -p | grep "hola"是否给出了一些结果。
标签: c++ c linux shared-libraries