views:

91

answers:

3

I have written a code where in it would take in a executable file and the [lib*.so] library as my arguments and link @ Run-time.

I want to also take in the function in the (*.o) file @ run-time and link it. But I don't know how to go about it.

EDIT 1: The function I'm trying to link is a part of the .o file in the lib*.so library. So I want to specify the library name and also the function name which is in the same library @ Run-Time.

For eg. If my library contains two functions(i.e *.o files) the linker should compile the function which I want to use @Run-Time.

I have posted the code,please help :

#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>    // use -ldl

typedef float (*DepFn)(short, short);

int main(int argc, char* argv[])
{
    void* lib;
    DepFn df;

    if(argc < 2)
        return printf("USAGE: %s lib-file\n", argv[0]);

    lib = dlopen(argv[1], RTLD_NOW);
    if(lib == NULL)
        return printf("ERROR: Cannot load library\n");

    df = dlsym(lib, "Depreciation");
    if(df)
    {
        short l, i;

        printf("Enter useful-life of asset: ");
        scanf("%hd", &l);

        for(i = 1; i <= l; i++)
        {
            float d = 100 * df(l, i);
            printf("%hd\t%.1f%%\n", i, d);
        }
    }
    else
        printf("ERROR: Invalid library\n");

    dlclose(lib);
}
+1  A: 

You cannot load a relocatable (*.o) at run time using standard functions. You need to make sure the object is compiled as position independent code (e.g. -fPIC) and then make a shared object out of it. Something like ld -shared -o foo.so foo.o may do the trick.

jilles
@jilles :please check EDIT 1
Pavitar
@jilles- Thankyou.I got your point :)
Pavitar
A: 

Based on your comments, you just want to link to your shared library,

change your code to:

extern float Depreciation(short i,k); //should rather go in a header file

int main(int argc, char* argv[])
{
    short l, i;

        printf("Enter useful-life of asset: ");
        scanf("%hd", &l);

        for(i = 1; i <= l; i++)
        {
            float d = 100 * Depreciation(l, i);
            printf("%hd\t%.1f%%\n", i, d);
        }
    }

Compile and link to your shared library:

 gcc -o myprogram myprogram.c -lXX

Your libXX.so would need to be installed in e.g. /usr/lib/ for the above to work See here for more info.

nos
A: 

If you need to take the function name at runtime, you need to pass it in argv[2], and instead of hardcoding function-name in the dlsym use argv[2].

if(argc < 3)
        return printf("USAGE: %s lib-file function-name\n", argv[0]);

    lib = dlopen(argv[1], RTLD_NOW);
    if(lib == NULL)
        return printf("ERROR: Cannot load library\n");

    df = dlsym(lib, argv[2]);
Searock