3 Answers
3

You aren't calling into ctest1.c or ctest2.c. Instead, you're creating ctest1 and ctest2 function pointers in prog.c, which you are not initializing, so it is causing a segmentation fault when you try to call them.

You need to declare your functions so prog.c can see them, and then link prog.c to the libraries (probably using the -l option to gcc).

@WhirlWind I have declared the functions as extern in prog.c and build the shared library as you mentioned , but still i get the segmentation fault
–
SirishApr 26 '10 at 5:52

1

The declaration void (ctest2)(int *); is just a funny way of writing extern void ctest2(int *); which has the merit of overriding any function-like macro ctest2 because the name is not followed by an open parenthesis. The definition of ctest1 is a function pointer which is not initialized and hence causes the seg fault.
–
Jonathan LefflerApr 26 '10 at 5:53

Try this after using the information WhirlWind gave you (the lines beginning with '#' are comments; you don't need to type them):

# Ensure that any shared objects you use are available in the current directory.
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
# Compile the library with a real name of "libctest.so.1.0.1"
# and a soname of "libctest.so.1".
gcc -shared -Wl,-soname,libctest.so.1 -o libctest.so.1.0.1 ctest1.o ctest2.o
# Create a symbolic link with soname as the name that points to the library.
# (libctest.so.1 -> libctest.so.1.0.1)
/sbin/ldconfig -v -n .
# Create a symbolic link using the "linker name" that points to the newly
# created library.
ln -sf libctest.so.1 libctest.so
# Compile your program.
gcc -Wall -L. prog.c -o prog -l ctest
# Run your program (it won't work without setting LD_LIBRARY_PATH because
# it won't be able to find your library).
./prog

That worked for me. It's a lot of work seemingly, but after a few trial-and-error cases, I think it becomes almost routine.

Edit: I almost forgot to mention that it seems a lot of tutorials suggest using the -fPIC option to generate position-independent code (don't confuse it with -fpic since that can make your resulting library less portable). It couldn't hurt to have it, but for simplicity I omitted it from the lines above.