top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to create a shared object using C progam on Linux machine?

+2 votes
553 views

Please share a sample program with detail code.

posted Nov 1, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes

A dynamic library (shared library) can be linked with an executable at runtime.
The code of a shared library is loaded into physical memory once and can be reused by multiple processes

Extension used for dynamic libraries is .so

Creation of dynamic libraries is done using the –shared switch with gcc

Important options of the gcc command:
shared : produce a shared object which can then be linked with other objects to form an executable
fpic: generate position-independent code (PIC) suitable for use in a shared library

a.out: libsample.so program.o
gcc –L. program.o –lsample

program.o: program.c
gcc –c program.c

libsample.so: a.o b.o
gcc –shared –o libsample.so a.o b.o

a.o: a.c
gcc –fpic –c a.c
b.o: b.c
gcc –fpic –c b.c

answer Nov 1, 2013 by Vikas Upadhyay
Similar Questions
+1 vote

I am a newbie and using fedora machine, please help with point by point C programming setup.

+4 votes

"Given an array of strings, find the string which is made up of maximum number of other strings contained in the same array. e.g. “rat”, ”cat”, “abc”, “xyz”, “abcxyz”, “ratcatabc”, “xyzcatratabc” Answer: “xyzcatratabc”

0 votes

My static library is present on path /root/xxx/lib and contains libabc.a libefg.a liblmn.a file and my shared library is present in /root/xxx named as libshared.so

I want to link shared library with static library. Please share the gcc command for the same.

+5 votes

Even I have similar problem:

int (*pfun)(void);
int *pInt = 0;
void fun1()
{
    int i = 5; /* Local to fun1*/

    printf("Outer function");
    pInt = &i; /* As I know address of local variable is valid till function execution */

    int fun2()
    {
      printf("innerfunction");
      printf("%d", *pInt);
    }
    /* fun2 address assign to pfun so that It can be called even after completion of fun1 */
    pfun = fun2;
}

int main()
{
    fun1();
    pfun();
    return 0;
}

Can someone please explain ? I am getting *pInt value 5.

...