Friday, April 16, 2010

Compiling Shared Libraries .so


Need to compile Library in Position independent code 

When the object files are generated, we have no idea where in memory they will be inserted in a program that will use them. Many different programs may use the same library, and each load it into a different memory in address. Thus, we need that all jump calls ("goto", in assembly speak) and subroutine calls will use relative addresses, and not absolute addresses. Thus, we need to use a compiler flag that will cause this type of code to be generated

gcc -fPIC -c util_file.c
gcc -fPIC -c util_net.c
gcc -fPIC -c util_math.c
gcc -shared libutil.so util_file.o util_net.o util_math.o
Why is this Required ??
dlopen()  --Thing is inspite of Loading library at begining . 
From program we can specify when to Load and unload a Library 
and what to use. 
dlopen returns a handler on success 
lib_handle = dlopen("/full/path/to/library", RTLD_LAZY); 

 
RTLD_LAZY  -- Lazy aproach --defining whether all 
symbols refered to by the library need to be checked immediately or When used 
dlopen() UNLOAD


Reference:
http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html

Thursday, April 8, 2010

Random C question

Q How to write Multi line MACRO ???  
#define MUL_LINE_MACRO(x)    do{  x=123; } while (0)
 http://c-faq.com/cpp/multistmt.html

Dont put ; after Macro let user put it  MUL_LINE_MACRO(x);
This is required as 
if in code macro is used in if else  condition like;
if (cond )
    MUL_LINE_MACRO(x);
else
   some ;
and macro also has an  ";"  then complilation fails 
if (cond )
      do{  x=123; } while (0);
  ; // this will cause compilation failure
else
   some ;