Showing posts with label linux. Show all posts
Showing posts with label linux. Show all posts

Sunday, February 08, 2009

Dynamic Load Library - Linux

Have you ever wondered, how to load, link and execute library functions when it is needed and unload it after it is used in Linux.

libdl - Library gives you this opportunity. For example:

* If you are writing an application which makes use of XML Parsing Library sparingly. You may want to load this XML Library when there is need and unload it afterwards.
* Or, you may want to load choose a particular library depending on the runtime parameters of an application.

libdl comes in handy, with only 3 interfaces with in the library. The following functions are defined in "dlfcn.h".

* dlopen - gain access to an executable object file
* dlsym - obtain the address of a symbol from a dlopen object
* dlclose - close a dlopen object
* dlerror - dlerror - get diagnostic information

void *handle;
int *iptr, (*fptr)(int);

/* open the needed object */
handle = dlopen("/usr/home/me/libfoo.so", RTLD_LOCAL | RTLD_LAZY);

/* find the address of function and data objects */
*(void **)(&fptr) = dlsym(handle, "my_function");
iptr = (int *)dlsym(handle, "my_object");

/* invoke function, passing value of integer as a parameter */
(*fptr)(*iptr);



Don't forget to set the LD_LIBRARY_PATH.

Thursday, February 05, 2009

Creating Static Libraries in Linux

add.c
=====

int add(int a, int b) {
return a+b;
}

int sub(int a, int b) {
return a-b;
}

>>gcc -c add.c // creates add.o


mul.c
=====

int mul(int a, int b) {
return a*b;
}

int div(int a, int b) {
return a/b;
}

>>gcc -c mul.c // Creates mul.o


Creating Archive
================

ar cr libaddmul.a add.o mul.o // Create and replace the obj files in the archive

ranlib libaddmul.a // generate index to archive

nm libaddmul.a // list symbols from object files

How to use the Static Library
=============================

math.c
======

#include "stdio.h"
#include "addmul.h"

int main() {
printf(" 3 + 5 = %d\n", add(3, 5));
printf(" 3 - 5 = %d\n", sub(3, 5));
printf(" 3 * 5 = %d\n", mul(3, 5));
printf(" 3 / 5 = %d\n", div(3, 5));
return 0;
}

addmul.h
========

extern int add(int, int);
extern int sub(int, int);
extern int mul(int, int);
extern int div(int, int);

gcc -o math math.c -L((libaddmul.a path)) -laddmul // compile math.c with addmul library

Sunday, February 10, 2008

Linux Kernel

Linux is Unix-like operating system. It is released under GNU GPL (General Public License). Linux Kernel was originally developed by Linux Trovalds. Linux is written in C Programming Language(GCC).

Simplified Linux Kernel
=======================
http://upload.wikimedia.org/wikipedia/commons/2/28/Linux_kernel_diagram.png

Linux Kernel Map
================
http://www.makelinux.net/kernel_map