Introduction to C in Linux/Unix COMP 1002/1402 Writing a Novel - - PDF document

introduction to c in linux unix
SMART_READER_LITE
LIVE PREVIEW

Introduction to C in Linux/Unix COMP 1002/1402 Writing a Novel - - PDF document

Introduction to C in Linux/Unix COMP 1002/1402 Writing a Novel Process Determine ideas Story features Write book (Mystery, Contact publisher metaphors) Editing Book (Novel) Book language (English, French) 1 Creating a program


slide-1
SLIDE 1

1

Introduction to C in Linux/Unix

COMP 1002/1402

Writing a Novel

Book

(Novel)

Process

Determine ideas Write book Contact publisher Editing

Story features

(Mystery, metaphors)

Book language

(English, French)

slide-2
SLIDE 2

2

Creating a program

Application Program Software Engineering

(process)

Application Smarts

(algorithms, data structures)

Coding

(high level language C)

Programming Languages

  • Machine languages

– Machine code – Assembly language

  • Higher level

languages

– Procedural language – Object Oriented

push ebx push esi push edi mov dword ptr [ebp-18h],esp mov eax,94h call 00410C30 mov dword ptr [ebp-30h],esp psquares=squares; /*fill array with squares of numbers*/ for(i=0;i<1000;i++) *(psquares++)=i*i; printf("\nWIDTH : "); scanf("%d",&WIDTH); printf("\nHEIGHT : "); scanf("%d",&HEIGHT);

slide-3
SLIDE 3

3

Machine Languages

  • Basic instructions sets
  • f chip
  • Unique to manufacturer
  • Each instruction is a

circuit

  • Examples

– Add, subtract, shift bits, load bits into cpu…

push ebx push esi push edi mov dword ptr [ebp-18h],esp mov eax,94h call 00410C30 mov dword ptr [ebp-30h],esp

psquares=squares; /*fill array with squares of numbers*/ for(i=0;i<1000;i++) *(psquares++)=i*i; printf("\nWIDTH : "); scanf("%d",&WIDTH); printf("\nHEIGHT : "); scanf("%d",&HEIGHT);

High Level Languages

  • Pascal, C, C++, Java, Cobol
  • Must be translated into Machine Language
  • Need translation programs (e.g. compilers)
  • Machine Code is executed
slide-4
SLIDE 4

4

History of C The C Language

  • Ken Thompson invents B (1967)
  • Dennis Ritchie develops C (1970)
  • C is high level language
  • Also Contains low level abilities
slide-5
SLIDE 5

5

Creating a Program

  • Create a text file with .c extension
  • “Compile” the program
  • The result : An executable program
  • Compiling is a multi-stage process

(many stages are sometimes automatic)

  • C Source Code used as input to compiler program.

– output :object code. – object code is essentially machine code + unresolved references.

  • Object code file and other object code files used as input to

linker.

– Output : machine code or load module.

  • Machine code is input to loader which loads code into memory
  • One typically ends up with 3 basic files.

– Source code, – object code and – load module (machine code). The load module is executable.

slide-6
SLIDE 6

6

Compiling A Simple Example : hello.c

#include <stdio.h> #include <stdlib.h> int main() { printf(“Hello World ! \n", name); return(0); }

slide-7
SLIDE 7

7

Preprocessing

  • Takes human readable source code

– Removes comments – Substitutes constants with values – Inserts files indicated by #include – Follows other directives

  • Inserts “#include”
  • Uses “#defines”
  • Processes “#if”
  • Outputs machine readable code
  • May rely on specific files (-I includes)

Compiling

  • Translates (converts) the preprocessed

code into object code (assembler)

  • Output is machine dependent

– Certain options occur here (-c -o) – Unresolved references (e.g., functions in

  • ther files)
slide-8
SLIDE 8

8

Compiling - Assembling

  • The assembler converts assembler into
  • bject files (.o files)
  • .o files are

– Machine dependent – Not executables (unresolved calls) – Can act as libraries of code

Linking

  • Linking produces executable from object

files

– Resolves unresolved references – Calls/include Necessary libraries – Combine all object files into a single executable file

  • Normal executable output is: a.out
slide-9
SLIDE 9

9

Stages

  • Compiling is either a:

– Single stage process – Two stage process

  • Many programs compile in one stage
  • Usefulness of .o files:

– Implies two stage process – (Preprocess, compile and assemble) then link later

Compiling in Linux

  • cc is the default compiler for Sun
  • gcc is the compiler from Gnu

Sigma01> gcc hello.c

Results in a.out

slide-10
SLIDE 10

10

Compiling hello.c

Sigma01> gcc -o hello hello.c

  • o means : Redirect the output

Creates “hello” as executable file

  • g means : Produce assoc. symbol table info.

Useful for debugging May not compile ( ) if there are errors (spelling, brackets, semi-colons…)

Running hello

After compiling you can run the program:

Sigma01> ./hello

If “.” is in your PATH then you can type:

Sigma01> hello

slide-11
SLIDE 11

11

Compiling hello.c

Sigma01> gcc –g –o hello hello.c

  • g creates symbol table in hello executable

Allows debugging programs to use hello Remember compiler only does basic checks

Debugging with gdb

  • When programs don’t work:

e.g. Produces Segmentation fault – Tries to write in memory it doesn’t own….

  • Runtime error doesn’t say anything
  • Program may not output anything

WORTH LEARNING THIS UTILITY !!!

slide-12
SLIDE 12

12

gdb commands

gdb <executable> help – get help list – lists program run – runs program break <line> -- sets a breakpoint backtrace – shows where program ended quit – end the program

A Simple Example : hello.c

#include <stdio.h> int main(int argc, char* argv[]) { char* name; strcpy (name, argv[1]); fprintf (stderr, "Your name is: %s\n", name); return(0); }

slide-13
SLIDE 13

13

A Simple Example : hello.c

argc : Automatically counts the no. of arguments to the program

Sigma01> hello there john peter smith

argc is automatically set to 4 argv[0] is set to “hello” (the executable name) argv[1] is set to “there” argv[2] is set to “john”...

Compling/Running : hello.c

  • Compile the above program as follows:

Sigma01> gcc –g -o hello hello.c

  • After compiling, if you run “hello” - you see

–Segmentation fault

  • A run-time error
  • Compiler cannot catch this.
  • Use utility (GDB) to trace the error’s cause
  • Can be very time consuming.
slide-14
SLIDE 14

14

Debugging : hello.c

  • Load gdb

Sigma01> gdb hello

  • Sigma01> is changed to (gdb)
  • Use the gdb commands (list/run/…)

Debugging : hello.c

(gdb) list

  • 1. int main(int argc, char* argv[])
  • 2. {
  • 3. char* name;
  • 4. strcpy (name, argv[1]);
  • 5. fprintf (stderr, "Your name is: %s\n",name);
  • 6. return(0);
  • 7. }

(gdb)

slide-15
SLIDE 15

15

Debugging : hello.c (run)

(gdb) run

Starting program: /home/John/Code/hello Program received signal SIGSEGV, Segmentation fault. 0x4007f2c0 in strcpy () from /lib/libc.so.6

(gdb) Message : Culprit is strcpy () Address : Culprit is at 0x4007f2c0 (in hex)

Debugging : hello.c (backtrace)

(gdb) backtrace

#0 0x4007f2c0 in strcpy () from /lib/libc.so.6 #1 0xbffffc4c in __DTR_END__ () from /lib/libc.so.6 #2 0x80485f6 in __libc_start_main () from /lib/libc.so.6 #3 0x80485f6 in ?? () Cannot access memory at address 0xe853.

(gdb)

  • Basically says : Culprit is argv[1] ; Make strcpy fail
  • Address of pointer “name” is 0xe853 (print it and see...)
  • Check the value of argv[1] by using a breakpoint
slide-16
SLIDE 16

16

Debugging : hello.c (breakpoint)

(gdb) break 3

Breakpoint 1 at 0x80788e1: file hello.c, line 3.

(gdb) run

The program being debugged has been started already. Start it from the beginning? (y or n) y Starting program: /home/John/Code/hello Breakpoint 1, main (argc=1,argv=0xbffffc4c) at hello.c:3 3 {

(gdb)

Debugging : hello.c (printing)

To see the contents of argv [1]

(gdb) print argv[1]

You will see the following on the terminal:

Cannot access memory at address 0xe853.

(gdb) quit Reason : Did not allocate the memory for “name” Solution : Should have done it using “malloc” (Later..)

slide-17
SLIDE 17

17

Compiling Multiple Programs

We transform the above simple hello.c program

  • A serious development project

– Multiple headers – Multiple object files – Worldwide source contribution – Integrated debugging symbols

Compiling Multiple Files

#include <stdio.h> int main() { printf( "Hello there from Sydney! \n"); Melbourne (); Canberra (); return(0); }

slide-18
SLIDE 18

18

Compiling Multiple Files

#include <stdio.h> int Melbourne () { printf("Hello there from Melbourne !\n"); return(0); }

Compiling Multiple Files

#include <stdio.h> int Canberra () { printf("Hello there from Canberra !\n"); return(0); }

slide-19
SLIDE 19

19

Compiling Multiple Programs

  • The "Hello World!" program has expanded
  • A somewhat larger tool.
  • It needs to be broken up into separate header

and C files for modularity (this might be unnecessary, but it is beneficial).

  • If broken into pieces - more difficult to compile
  • Have to use the 'make' utility.

Compiling Multiple Programs

To create an executable file named hello : Type Sigma01> gcc –o hello hello1.c hello2.c hello3.c To run the program, simply Type : Sigma01> hello This will output on the terminal:

  • Hello there from Sydney!
  • Hello there from Melbourne!
  • Hello there from Canberra !
slide-20
SLIDE 20

20

Method 2 : Multiple Programs

To create an executable file named hello : Type Sigma01> gcc –c hello1.c Sigma01> gcc –c hello2.c Sigma01> gcc –c hello3.c To link the program, simply Type : Sigma01> gcc –o hello hello1.o hello2.o hello3.o To run the program, simply Type : Sigma01> hello

Compiling Multiple Programs

Compile all three at once with -g option: Sigma01> gcc -g -o hello hello1.c hello2.c

hello3.c

slide-21
SLIDE 21

21

Compiling Multiple Programs

As before, this can be done in two stages: 1) Creates Objects first

Sigma01> gcc -g -c hello1.c Sigma01> gcc -g -c hello2.c Sigma01> gcc -g -c hello3.c

2) Links Objects

Sigma01> gcc -g -o hello hello1.o hello2.o

hello3.o

Using make

Step 1: Create a file called Makefile Step 2: Add the example as given below Step 3: When finished save file and exit. Step 4: At the command line type make It will build the hello executable

slide-22
SLIDE 22

22

The file makefile

hello : hello1.o hello2.o hello3.o gcc -o hello hello1.o hello2.o hello3.o # generate object file for hello1.c hello1.o: hello1.c gcc -c hello1.c # generate object file for hello2.c hello2.o: hello2.c gcc -c hello2.c # generate object file for hello3.c hello3.o: hello3.c gcc -c hello3.c

Rules for make

  • Lines with : are dependency lines

– Left of : is the target – Right of : are the dependencies – Dependency line says “the target depends

  • n the sources”

hello : hello1.o hello2.o hello3.o

  • After each line use a carriage return
slide-23
SLIDE 23

23

Rules for make

  • On the second line, you must tab once
  • Enter the command line syntax for the

command used to build that file.

  • Without a tab, it will not work.

gcc -o hello hello1.o hello2.o hello3.o

Rules for make

  • This “command” line will be executed,

even if it doesn't create the file.

  • Lines are continued with \ (not <CR>)
  • Comments begin #
  • To run :

Sigma01> make

slide-24
SLIDE 24

24

Dynamic Loader

  • When programs are compiled under

Linux, they usually use pieces of code (functions) from external libraries.

  • When such programs are run, those

libraries must be found and the required functions loaded into memory.

  • This is the job of the Dynamic Loader.

Chapter Summary

Here are some sources re. Linux : http://humbolt.geo.uu.nl/Linux-MM/ http://members.aa.net/~swear/pedia/index.html. http://www.mainmatter.com/ http://www.linuxdoc.org/ http://www.linuxbox.com/~taylor/4ltrwrd/ http://www.stuwww.kub.nl/people/b.vannunen/linux- man.php3 http://www.linuxdoc.org/nlm/