Friday, August 27, 2010

Creating Shared Libraries under MAC OS X

One of my friend who has started to work on a Qt project on MAC OS X ( Snow leopard ) asked me to explain the steps for creating a Shared library in MAC OS X. Here is a sample program which i wrote to explain him the stuff

////////////
// test.cpp
// Source code of a small Shared library
//
//
// Written by Praseed Pai K.T.
// http://praseedp.blogspot.com
//
// At the MAC OS X terminal
// ------------------------
// g++ -c -fPIC test.cpp
// g++ -dynamiclib -o libTest.so test.o
//
// This will produce libTest.so
//
//
//
#include <stdio.h>

extern "C" int Add(int a , int b )
{
return a+b;
}


In GNU Linux , we use -shared as the flag while creating the .so file. In MAC OS X , we need to give -dynamiclib instead.
Also given below is the calling program

////////////////
// caller.cpp
//
// Written by Praseed Pai K.T.
// http://praseedp.blogspot.com
//
//
// At the MAC OS X Terminal
// ------------------------
//
// g++ caller.cpp -o caller.exe ./libTest.so
// ./caller.exe
//
#include <stdio.h>

extern "C" int Add(int a , int b );


int main( int argc , char **argv )
{
printf("The add is %d + %d = %d \n",2,3,Add(2,3));

}


Happy Coding !

0 comments: