Sunday, June 6, 2010

How to write a C program on Linux

If you are a newbie in Linux, you probably chose Linux for programming. It is fun and way too easy to write programs in Linux than dealing with Windows based programming tools (exclude MS IDEs). I will go through basic tools that almost all Linux distributions come bundled with. First one is an editor and second one is a compiler.

Editor:
You need a text editor to write your programs, right? A Text editor is an application that lets you write program and then you can use this program to compile and run using compilers. If you are migrating from Windows, an example of an editor is notepad, or the IDE's such as Visual Studio have in built ediotr.

We are going to talk about Vi editor. You must have vi editor installed on your Linux distro by default. All you need to do is to open a terminal (Shell). Once you have opened it you will see a command prompt. You might see something like:

user$

This is similar to the windows command prompt like:

C:\

For all our examples you will see this prompt. The command next to it are the ones you need to type. The next step is to create a program. Let us say you want to create a file named "hello.c". To create it you need to type the following command on command prompt:

user$ vi hello.c

This will open a blank page on your terminal. You want to write your program. Vi is a command/text based editor. To start writing you need to tell Vi that you need to start writing. For that you press "i" (lowercase i) and you will notice that the mode has changed to Insert mode (look at bottom left or right corner).

After that you can start writing your program. For example you can type:

#include

void main(int argc, char *argv[])
{
printf("Hello World!");
}

Note that sometimes arrow keys might not work. You will have to use j,k,l,m as replacement to arrow keys. If you want to delete one character press "ESc" key to come out of insert mode and then press "x" key to delete that character. Then to continue typing press "i" to go back to insert mode. Similarly to delete an entire line come out of insert mode and press "dd" to delete that line. Then go back to insert mode and keep typing. Similarly copy is "yy" and paste is "P". "dd" is not actually delete but cut, as you can paste the line you cut using "dd" too.

A complete list of key bindings can be found at the end of this post. Once youa re done writing your program you need to save it. For that press ":w". The ":" colon is simply to tell Vi that you want to give a command rather than doing somethign with the text you have written.
This will save whatever you have written to the file "hello.c". If you have completed writing your program and want to run it you need to quit Vi. To quit Vi you need to type ":q". Make sure you save your file before quitting. If you want to save and quit do ":wq". This will make sure you do not lose anything.

Compile:
This will take you back to the prompt. If you give the command "ls" it will list the file in your current directory. You will see the file hello.c listed there. That means the file was saved. We are ready to run our c program. To run a C program you need to compile it first, which will give you an executable file. You will then run this executable. The steps to compile a program are:

user$ gcc hello.c -o hello

gcc is the compiler that we are using. You must have it n your distro of linux. hello.c is the file that we need to compile. "-o hello" tells the compiler that you want the executable to be of the name hello (-o => output). If you type the ls command

user$ ls

Running a program:
you will see a new file named hello in the list besides hello.c. This is your executable file. To run this file type:

user$: ./hello

you will see the output of your program. It sounds complicated but trust me if you do it few times you will get used to it and everything will be a child's play. At least here you see what is actually ahppening that stupid programs which do everything automatically and you think your programs were run by magic.

If you want to change your program again say

user$ vi hello.c

Remember what does it do? It will open the file again and you can modify it as you want. If you don't want to use vi you can opt for other text editors, similar to the ones like notepad on linux. Type your program and save it in your home directory. Then do the "ls" command and you shall find it in your list. Rest all commands will still work.


List of key bindings for vi:

Key
Action
Followed by
a
enter insertion mode after current character
text, ESC
b
back word

c
change command
cursor motion command
d
delete command
cursor motion command
e
end of word

f
find character after cursor in current line
character to find
g
UNBOUND

h
move left one character

i
enter insertion mode before current character
text, ESC
j
move down one line

k
move up one line

l
move right one character

m
mark current line and position
mark character tag (a-z)
n
repeat last search

o
open line below and enter insertion mode
text, ESC
p
put buffer after cursor

q


r
replace single character at cursor
replacement character expected
s
substitute single character with new text
text, ESC
t
same as "f" but cursor moves to just before found character
character to find
u
undo

v
UNBOUND

w
move foreward one word

x
delete single character

y
yank command
cursor motion command
z
position current line
CR = top; "." = center; "-"=bottom
A
enter insertion mode after end of line
text, ESC
B
move back one Word

C
change to end of line
text, ESC
D
delete to end of line

E
move to end of Word

F
backwards version of "f"
character to find
G
goto line number prefixed, or goto end if none

H
home cursor - goto first line on screen

I
enter insertion mode before first non-whitespace character
text, ESC
J
join current line with next line

K
UNBOUND

L
goto last line on screen

M
goto middle line on screen

N
repeat last search, but in opposite direction of original search

O
open line above and enter insertion mode
text, ESC
P
put buffer before cursor

Q
leave visual mode (go into "ex" mode)

R
replace mode - replaces through end of current line, then inserts
text, ESC
S
substitute entire line - deletes line, enters insertion mode
text, ESC
T
backwards version of "t"
character to find
U
restores line to state when cursor was moved into it

V
UNBOUND

W
foreward Word

X
delete backwards single character

Y
yank entire line

Z
first half of quick save-and-exit
"Z"
0
move to column zero

1-9
numeric precursor to other commands
[additional numbers (0-9)] command

(SPACE) move right one character

!
shell command filter
cursor motion command, shell command
@
vi eval
buffer name (a-z)
#
UNBOUND

$
move to end of line

%
match nearest [],(),{} on line, to its match (same line or others)

^
move to first non-whitespace character of line

&
repeat last ex substitution (":s ...") not including modifiers

*
UNBOUND

(
move to previous sentence

)
move to next sentence

\
UNBOUND

|
move to column zero

-
move to first non-whitespace of previous line

_
similar to "^" but uses numeric prefix oddly

=
UNBOUND

+
move to first non-whitespace of next line

[
move to previous "{...}" section
"["
]
move to next "{...}" section
"]"
{
move to previous blank-line separated section
"{"
}
move to next blank-line separated section
"}"
;
repeat last "f", "F", "t", or "T" command

'
move to marked line, first non-whitespace
character tag (a-z)
`
move to marked line, memorized column
character tag (a-z)
:
ex-submode
ex command
"
access numbered buffer; load or access lettered buffer
1-9,a-z
~
reverse case of current character and move cursor forward

,
reverse direction of last "f", "F", "t", or "T" command

.
repeat last text-changing command

/
search forward
search string, ESC or CR
<
unindent command
cursor motion command
>
indent command
cursor motion command
?
search backward
search string, ESC or CR
^A
UNBOUND

^B
back (up) one screen

^C
UNBOUND

^D
down half screen

^E
scroll text up (cursor doesn't move unless it has to)

^F
foreward (down) one screen

^G
show status

^H
backspace

^I
(TAB) UNBOUND

^J
line down

^K
UNBOUND

^L
refresh screen

^M
(CR) move to first non-whitespace of next line

^N
move down one line

^O
UNBOUND

^P
move up one line

^Q
XON

^R
does nothing (variants: redraw; multiple-redo)

^S
XOFF

^T
go to the file/code you were editing before the last tag jump

^U
up half screen

^V
UNBOUND

^W
UNBOUND

^X
UNBOUND

^Y
scroll text down (cursor doesn't move unless it has to)

^Z
suspend program

^[
(ESC) cancel started command; otherwise UNBOUND

^\
leave visual mode (go into "ex" mode)

^]
use word at cursor to lookup function in tags file, edit that file/code

^^
switch file buffers

^_
UNBOUND

^?
(DELETE) UNBOUND




UNBOUND - this key is not normally bound to any vi command
word - a lower-case word ("w", "b", "e" commands) is defined by a consecutive string of letters, numbers, or underscore, or a consecutive string of characters that is not any of {letters, numbers, underscore, whitespace}
Word - an upper-case word ("W", "B", "E" commands) is a consecutive sequence of non-whitespace.
sentence
paragraph
cursor motion command - any command which positions the cursor is ok here, including the use of numeric prefixes. In addition, a repeat of the edit command usually means to apply to the entire current line. For example, "<<" means shift current line left; "cc" means replace entire current line; and "dd" means delete entire current line.

    5 comments:

    1. The program won't compile without the header file after the #include statement.

      ReplyDelete
    2. Dear Anony,

      Thank you for bringing this up. I don't know how did I forget that.

      Regards,
      Programmer

      ReplyDelete
    3. Thumbs up.
      but can i change the settings of these keys .
      it is not easy to digest

      ReplyDelete
    4. Dear Anony,

      Try to get used to it as this is the combination used by millions of techies. It is only difficult at the beginning.

      - Regards,
      Dinesh

      ReplyDelete