A Developer's Diary

Showing posts with label Linux. Show all posts
Showing posts with label Linux. Show all posts

May 4, 2011

Static Library - An Introduction

Static library is a group of object files bundled together in an archive by the archiver program. The static libraries have a .a extension.

Advantages
1. The executable is not dependent on any library as the library code is included in the binary
2. In some cases performance improvement
Command for creating a static library
ar rcs -o libmylibrary.a file1.o file2.o file3.o

Steps for generating the static library libemployee.a for the Employee Program written in the previous post

1. Compiling source files to object files
g++ -Wall -c -fPIC -O -I. -o Employee.o Employee.cpp
2. Command for building the archive file libemployee.a
ar -rcs -o libemployee.a Employee.o

Read more ...

May 3, 2011

Shared Library - An Introduction

A shared library is a library required by an executable to run properly. Such executables are called incomplete executables as they call routines present in the shared library code. The executables generated from the shared library are smaller in size than the ones generated from a static library

When an executable built with shared library is run, the dynamic loader identifies the list of dependent libraries to be loaded and searches for them in the standard default locations and the locations pointed to by the environment variable LD_LIBRARY_PATH (Linux), SHLIB_PATH (HP-UX), LIBPATH (AIX)

Shown below is the Employee class which we will use to generate the shared library libemployee.so

 1 #ifndef _Employee_H_
 2 #define _Employee_H_
 3 
 4 //File: Employee.h
 5 
 6 #include <iostream>
 7 
 8 class Employee
 9 {
10   public:
11       Employee();
12       Employee(const std::string name, int age);
13       virtual ~Employee();
14 
15       //Modifiers
16       void setName(const std::string name);
17       void setAge(int age);
18 
19       //Accessors
20       const char* getName() const;
21       int getAge()          const;
22 
23   private:
24       std::string m_name;
25       int m_age;
26 };
27 
28 #endif //_Employee_H_

 1 #include "Employee.h"
 2 //File: Employee.cpp
 3 
 4 Employee::Employee()
 5 {
 6 }
 7 
 8 Employee::Employee(const std::string name, int age)
 9 {
10     m_name = name;
11     m_age = age;
12 }
13 
14 Employee::~Employee()
15 {
16 }
17 
18 void Employee::setName(const std::string name)
19 {
20     m_name = name;
21 }
22 
23 void Employee::setAge(int age)
24 {
25     m_age = age;
26 }
27 
28 const char* Employee::getName() const
29 {
30     return m_name.c_str();
31 }
32 
33 int Employee::getAge() const
34 {
35     return m_age;
36 }

Compiling the Employee source files to object files
g++ -Wall -c -fPIC -O -I. -o Employee.o Employee.cpp

Linking the object files to generate the shared library libemployee.so
gcc -o libemployee.so Employee.o -shared -fPIC -Wl,-rpath,. -L. -lstdc++

Read more ...

Mar 15, 2011

Customize Cygwin/Linux command prompt

From the bash manual, the following environment variables control the display of prompt in a Cygwin or Linux terminal namely PS1, PS2, PS3, PS4.
Note: For referring the bash manual type info bash

Key Points
1. PS1 : The value of this parameter is expanded and used as the primary prompt string. It's default value is '\s-\v\$ '
2. PS2 : The value of this parameter is expanded as with PS1 and used as the secondary prompt string. The default value is >
3. PS3 : The value of this variable is used as the prompt for select command. If this variable is not set, select command prompts with #?
4. PS4 : The prompt is used when you have tracing enabled for debugging the bash scripts. The PS4 value is printed each time the command is echoed on the screen. The default value is +

a) PS1 demo
1. Identify the current prompt setting in your Cygwin/Linux terminal by typing echo $PS1
2. Make the modifications to PS1 and export the new PS1 variable. Your prompt should change immediately


b) PS2 demo
When executing interactively, bash displays the primary prompt PS1 when it is ready to read a command, and the secondary prompt PS2 when
it needs more input to complete a command.


c) PS3 demo
This prompts user to provide an input.
#!/bin/bash

LINUX=linux
WIN32=win32
HPUX=hpux
SUNOS=sunos
AIX=aix
QUIT=quit

OPTIONS="\
    $LINUX \
    $WIN32 \
    $HPUX \
    $SUNOS \
    $AIX \
    $QUIT"

select option in $OPTIONS;
do
  echo "${option}"  
  if [ "${option}" = "quit" ]; then
    exit
  fi
done
Output:


d) PS4 demo
Enable tracing by typing the following command set -x


Bash allows these prompt strings to be customized by inserting a number of backslash-escaped special characters that are decoded as follows:

\a     an ASCII bell character (07)
\d     the date in "Weekday Month Date" format (e.g., "Tue May 26")
\D{format}
    the format is passed to strftime(3) and the result is inserted into the prompt  string;  an  empty  format  results  in  a locale-specific time representation.  The braces are required
\e     an ASCII escape character (033)
\h     the hostname up to the first `.'
\H     the hostname
\j     the number of jobs currently managed by the shell
\l     the basename of the shell's terminal device name
\n     newline
\r     carriage return
\s     the name of the shell, the basename of $0 (the portion following the final slash)
\t     the current time in 24-hour HH:MM:SS format
\T     the current time in 12-hour HH:MM:SS format
\@     the current time in 12-hour am/pm format
\A     the current time in 24-hour HH:MM format
\u     the username of the current user
\v     the version of bash (e.g., 2.00)
\V     the release of bash, version + patch level (e.g., 2.00.0)
\w     the current working directory, with $HOME abbreviated with a tilde
\W     the basename of the current working directory, with $HOME abbreviated with a tilde
\!     the history number of this command
\#     the command number of this command
\$     if the effective UID is 0, a #, otherwise a $
\nnn   the character corresponding to the octal number nnn
\\     a backslash
\[     begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt
\]     end a sequence of non-printing characters

References:
1. bash manual

Read more ...

Mar 4, 2011

Makefile tutorial for beginners

The purpose of the make utility is to determine automatically which pieces of your large program needs to be re-compiled, and issue the commands to recompile them. The make program uses the makefile instructions and the last modified time of the files to decide which of the files needs to be updated.
A makefile tells make what to do. The make utility executes commands in the makefile to update one or more targets. If -f option is not provided, make looks for the makefiles GNUmakefile, makefile, and Makefile, in that order.

Key Points
1. Make is a software engineering tool which helps simplifies the process of software development
2. Makefiles can be used to automate the build process (Generation of binary from source files)
3. The programmer does not need to type the complex compiler commands and flags to be used during compilation

1. Variables
1. A variable in a makefile can be a recursively expanded variable NAME = value or a simply expanded variable NAME := value
2. The variable's value can be accessed using $(NAME) or ${NAME}
3. As a convention, the variable names are always written in uppercase.
4. Variable names are case-sensitive and should not contain other than letters, numbers and underscores as they may have a special meaning
5. Setting a variable if not already set use ?= e.g. NAME ?= value

Note: You cannot append a value at the end of the recursively expanded variable using CC = $(CC) -O2. This will end up in an infinite loop as make will continue expanding this variable until it cannot be expanded anymore. To overcome this problem, we use simply expanded variables to append values at the end as shown

CC := g++ -o
CC += $(CC) -O2

2. Explicit Rules
Explicit rules tell make which files depend on the compilation of other files and the commands required to compile those files. They take the following form:

targetfile : dependentfiles
[TAB]commands
...
[TAB]commands 

3. Implicit Rules or Suffix Rules
Implicit rules are similar to explicit rules except that they are listed without commands. The make utility makes uses of the file suffixes to determine what commands to execute on the source files

hello.o : hello.c
Running make will cause the following command to be executed cc -c -o hello.o hello.c

Common variables used by implicit rules:

AR  : archive program, default ar
CC  : compiling c program, default cc
CXX : compiling c++ program, default g++
CPP : c preprocessor, default $(CC) -E
RM  : remove, default rm -f

Flags used by the programs above

ARFLAGS  : flags for the archive program, default rv
CFLAGS   : flags for the c compiler
CXXFLAGS : flags for the c++ compiler
CPPFLAGS : flags for the c preprocessor
LDFLAGS  : flags for the linker

Some of the old fashioned suffix rules for C and C++ are:

Compiling C Programs
file.o is automatically built from file.c. $(CC) -c $(CPPFLAGS) $(CFLAGS)

Compiling C++ Programs
file.o is automatically built from file.cc. $(CXX) -c $(CPPFLAGS) $(CXXFLAGS)

Linking Object Files
file is automatically generated from file.o by running the linker (ld). $(CC) $(LDFLAGS) file.o $(LOADLIBS) $(LDLIBS)

The default suffix list for common C and C++ programs include .out, .a, .o, .c, .cc, .C, .def, .h. The complete list can be found out here

The above catalogue of implicit rules are always available unless makefile explicitely overrides them. Running make with -r or --no-builtin-rules option cancels all predefined rules

Implicit rules can also be disabled by disabling default suffixes and having only the suffixes you need

.SUFFIXES:    # Delete the default suffixes
.SUFFIXES: .c .cpp .o .h       # Define our suffix list

Inference Rules: Inference rules are rules distinguished by the use of the character “%” in the dependency line. The “%” (rule character) is a wild card, matching zero or more characters. As an example, here is an inference rule for building .obj files from .c files:
%.obj : %.c
        $(CC) $(CFLAGS) –c $(.SOURCE) 

4. Phony Targets
A phony target is one that is not really the name of the target file. It is a request for executing a set of commands that should not create the target file name. As the target file will never exist, the commands will be executed always e.g.

clean:
        rm *.o temp

You can also explicitely declare a target as phony using the special target .PHONY

.PHONY = clean

5. Comments
A comment starts with # character in a makefile

6. Substitution References
A substitution reference has the form $(file:.c=.o). The below example sets OBJFILES to a.o b.o c.o

SRCFILES = a.c b.c c.c
OBJFILES = $(SRCFILES:.c=.o)
SRCFILES = a.c b.c c.c
OBJFILES = $(SRCFILES:%.c=%.o)

Read more ...

Mar 27, 2010

vimrc explained

VIM editor is one of the most popular text editor amongst the developers. At first look, it appears to be a daunting task to get used to it but once you get the hang of the unlimited functionality it offers at your hand, there is no going back and you will fell in love with the tool

A customized ~/.vimrc file

:syntax on        "Turn on syntax highlighting
:set laststatus=2 "Always show status line

:set autowrite    "Automatically write a file when leaving a modified buffer
:set confirm      "Start a dialog when a command fails (here when quit command fails)
:set tabstop=4    "Number of spaces a TAB in the text stands for

:set shiftwidth=4 "Number of spaces used for each step of (auto)indent
:set hlsearch     "Have vim highlight the target of a search
:set incsearch    "Do incremental searching

:set ruler        "Show the cursor position all the time
:set number       "Show line numbers
:set ignorecase   "Ignore case when searching

:set title        "Show info in the window title
:set titlestring=PANKAJ:\ %F   
    "Automatically set screen title

:set noautoindent
:set nosmartindent
:set nocindent


"Indent only if the file is of type cpp,c,java,sh,pl,php,asp
:au FileType cpp,c,java,sh,pl,php,asp  set autoindent
:au FileType cpp,c,java,sh,pl,php,asp  set smartindent
:au FileType cpp,c,java,sh,pl,php,asp  set cindent

"Wrapping long lines
:set wrapmargin=4   "Margin from the right in which to break a line. Set this value to 4 or 5

:set textwidth=70   "Line length above which to break a line

"Defining abbreviations
:ab #d #define
:ab #i #include


"Defining abbreviations to draw comments
:ab #b /********************************************************
:ab #e ********************************************************/
:ab #l /*------------------------------------------------------*/

"Converting tabs to spaces
:set expandtab

VIM Editor Tips

Navigating through VIM

Down (j), Up (k), left (h), right (l)
w (word forward), b (word backward)
W (word forward skip punctuation), B (word backward skip punctuation)
Page Down (Ctrl-f)
Page Up (Ctrl-b)
End of Line ($)
Start of Line (0)
Start of document (gg)
End of Document (G)
Jump to last place that you made an edit (g;)


Copy Pasting Contents

Surprisingly VIM inserts a lot of extra spaces when code is pasted from other applications. This can be corrected by executing the following in VIM mode

:set paste
OR
gg=G

Indentations can be corrected by running the following command in the system

indent -kr filename


Working with Visual Blocks

It is a feature that allows you to mark a block of text and perform editing operations on them. To enter visual blocks mode, press Ctrl+v, then use hjkl or arrow keys to highlight a block of text. Now operate on the first highlighted line as if you were in normal mode

Visual mode (v)
Visual line mode (V)
Visual block mode (Ctrl-v)


Converting tabs to spaces

Make sure you have :set expandtab set in your .vimrc file or otherwise execute set expandtab in normal mode and then run the following command to convert all tabs to spaces

:retab


Wrap a long line

Use (gq) to wrap the highlighted peice of text


Auto-Complete

Start typing the variable/function names and then (Ctrl-n) or (Ctrl-p) next and previous


Delete

delete character (x)
delete word (dw)
delete line (dd)


Auto-Indent

line (==)
entire document (gg=G)


Find/Replace

%s/oldword/newword/g OR %s#oldword#newword#g
%s/oldword/newword/gc OR %s#oldword#newword#gc


Split Windows

Horizontal Windows :split
Vertical Windows :vs
Shifting between Windows (Ctrl-shift-ww)


Map Commands

If you find yourself re-typing the same command over and over, map it to one of the function keys as follows:

:map <fx> cmd

This maps the command cmd to function key Fx. For example, to map F5 to the command :!gcc -c % (compiles the current file) in normal mode


Code Folding

For large code blocks, you might want to fold/hide away certain functions temporarily. To fold a selection, select it in visual then (zf). To open a fold (zo)


Changing the Line Number Background and Foreground color

:highlight LineNr guibg=grey
:highlight LineNr guifg=blue
:highlight LineNr ctermfg=white ctermbg=grey


Read more ...

Apr 14, 2009

Connect to GNOME Display Manager (GDM) using XMing X Server for Windows



The GDM display manager implements all significant features required for managing attached and remote displays.

The GDM daemon can be configured to listen for and manage X Display Manage Protocol (XDMCP) requests from remote displays.

GDM has a number of configuration interfaces. These include scripting integration points, daemon configuration, greeter configuration, general session settings, integration with gnome-settings-daemon configuration, and session configuration.
By default XDMCP support is turned off, but can be enabled if desired.



Daemon Configuration for XDMCP

The GDM daemon is configured using the /etc/gdm/custom.conf file. Default values are stored in GConf in the gdm.schemas file. It is recommended that end-users modify the /etc/gdm/custom.conf file because the schemas file may be overwritten when the user updates their system to have a newer version of GDM.

Note that older versions of GDM supported additional configuration options which are no longer supported in the latest versions of GDM.

The /etc/gdm/custom.conf supports the "[daemon]", "[security]", and "[xdmcp]" group sections


To enable XDMCP Support add the following in custom.conf file

[xdmcp]
Enable=true

[security]
DisallowTCP=false
AllowRemoteRoot=true
Restart X Windows using the command gdm-restart

Connecting to GDM through XMing X Server

Step1: Download XMing X Server executable for Windows from here and install it.

Step2: Launch XLaunch. Select Fullscreen


Step3: Select Open Session via XDMCP


Step4: Enter hostname or ip address


Step5: Click Next


Step6: Click Finish


Step7: You have successfully connected through XMing



References:
1. GNOME Documentation
2. Comparing XDM, GDM, KDM and WDM

Read more ...

Apr 9, 2009

Using awk to calculate sum/average

awk is a small powerful tool for processing column oriented text data.
Suppose I have file Marks.txt whose contents are




Use the following command to calculate the sum of the entries in column 3


cat Marks.txt | awk '{sum+=$3} END {print "Total=", sum}'



To get the average, use the following command

cat Marks.txt | awk '{sum+= $3} END {print "Average=", sum/NR}'



Read more ...

Mar 26, 2008

Finding Linux Version

Linux Release Version can be obtained by executing


cat /etc/redhat-release


For getting linux kernel versions execute

uname -a or uname -r

Read more ...