我已经浏览了 StackOverflow 和 Ask Ubuntu 上的所有解决方案。
我有一个 Go 程序:
package main
import "C"
//export Getint
func Getint() int {
return 2
}
func main() {}
我已经生成了 .so
文件,名称为 t.so 和头文件
t.h`
现在我想在我的 C 程序中使用这个函数。
我已经编写了代码,但我不知道如何执行它。
#include <stdio.h>
#include <t.h>
int main()
{
int a;
a=Getint();
printf("number : %d",a);
return 0;
}
当我执行它时
gcc c.c t.so
生成a.out
文件
但是在使用 ./a.out
运行 a.out
时它给出了一个错误:
./a.out
Error while loading shared libraries: t.so: can not open shared object file: no such file or directory exists.
然后我尝试了:
gcc -c c.c -l t.so
因此它生成了c.o
文件,而且它是不可执行的。
最佳答案
你应该使用 linker option -rpath
,它告诉链接器在可执行程序中添加信息,在哪里可以找到像 .so
文件这样的运行时库。
这可以使用 GCC 选项 -Wl
来完成,它指示 GCC 前端程序将选项传递给链接器:
$ gcc c.c t.so -Wl,-rpath=$(pwd)
这会将 -rpath=$(pwd)
传递给链接器,$(pwd)
会导致 shell 调用 pwd
命令返回当前目录。
只要您不移动库,程序就应该可以运行。
您也可以使用环境变量LD_LIBRARY_PATH
,但它是not recommended .
关于c - 如何使用.so文件运行c程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34991934/