Sunday, October 24, 2021

[SOLVED] How to run c program with .so file

Issue

I have gone through all the solutions on StackOverflow as well as Ask Ubuntu.

I have a Go program:

package main

import "C"

//export Getint
func Getint() int {
        return  2
}

func main() {}

and I have generated .so file for the same with name t.so and header filet.h`

Now I would like to use this function in my C program.
I have written the code but I don't know how to execute it.

#include <stdio.h>
#include <t.h>
int main()
{
int a;
a=Getint();
printf("number : %d",a);
return 0;
}

When I execute it with

gcc c.c t.so

it generates a.out file

but at the time of running a.out with ./a.out it gives an error:

./a.out
Error while loading shared libraries: t.so: can not open shared object file: no such file or directory exists.

then I tried with:

gcc -c c.c -l t.so

So it generates c.o file and it is not executable.


Solution

Most probably your loader cannot find the library. Try to put the path to the directory where the libarry is located to LD_LIBRARY_PATH prior to run your binary.

export LD_LIBRARY_PATH=/path/to/my/library
./a.out


Answered By - dmi