1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*****************************************************
 * When I run: 
 * ./multiply 3 3
 * I get:
 * 3 x 3 = 0 
 * While I expect:
 * 3 x 3 = 9
 **/

/*****************************************************
 * main.c 
 * Compiled with: gcc -Wall -g -o multiply main.c
 **/

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include "multiply.h"

int main(int argc, char* argv[])
{
        void *lib_handle;
        int   ret, local;
        int  (*fptr)(int);

        if (argc < 3) {
                fprintf(stderr, "Usage: %s <a> <b> where a, b are integers\n", argv[0]);
                exit(1);
        }
        global = atoi(argv[1]);
        local  = atoi(argv[2]);

        lib_handle = dlopen("multiply.so", RTLD_LAZY);
        if (! lib_handle) {
                fprintf(stderr, "%s\n", dlerror());
                exit(1);
        }

        *(void **)(&fptr) = dlsym(lib_handle, "multiply");

        ret = (*fptr)(local);

        dlclose(lib_handle);
        printf("%d x %d = %d\n", global, local, ret);

        return 0;
}

/*****************************************************
 * multiply.c 
 * Compiled as a dynamic library with: 
 * gcc -Wall -rdynamic -g -fPIC -c multiply.c
 * gcc -shared -rdynamic -Wl -o multiply.so multiply.o
 **/

#include "multiply.h"

int multiply(int local)
{
        return local * global;
}

/*****************************************************
 * multiply.h
 **/

#ifndef _DL_H

int multiply(int local);

int global;

#define _DL_H
#endif