how to call C subroutine from object file at runtime

597 Views Asked by At

I am trying out a C program. I have a c subroutine sub defined in a file sub.c as follows:

int sub (int a, int b)
{
   return a + b;
}

I compile this file and produce an object file sub.o.

I want to call the subroutine sub that sits in sub.o from my main subroutine that is defined in another file named main.c.

Normally I'd do it just as follows:

int main ()
{
   int r = sub(10, 20);
   printf("result = %d\n", r);
   return 0;
}

and then compiling as below: gcc -o main main.c sub.o

What I want to do is be able to call the subroutine sub by directly reading its code from the object file sub.o at runtime. I know I can use shared object based solution. But is there a way which does not require me to implement a full support for shared object and still allows me to load the code from an object file to some place in RAM and execute it by jumping to that location? In short I am looking for some sort of quickfix that allows me to do this.

I know objdump allows me to extract the executable code from the .o file but I don't what to do with it later. Any help or pointers in right direction are welcome.

Note: I want to do this on any Linux based system in user space.

0

There are 0 best solutions below