32
1 Lab 2: The Unix environment, Lab 2: The Unix environment, Using vi, C programming Using vi, C programming SITE, uOttawa SITE, uOttawa

Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

  • Upload
    skyler

  • View
    39

  • Download
    0

Embed Size (px)

DESCRIPTION

Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa. Practical tools. Editor Vi (emac) Compiler gcc Makefile make Debugging gdb. Using C/Unix/Linux at SITE. $ ssh linux. Vi Editor. A screen-based editor used by Unix users An experience with vi Starting the editor - PowerPoint PPT Presentation

Citation preview

Page 1: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

1

Lab 2: The Unix environment, Lab 2: The Unix environment, Using vi, C programmingUsing vi, C programming

SITE, uOttawaSITE, uOttawa

Page 2: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

2

Practical toolsPractical tools

EditorEditor Vi (emac)Vi (emac)

CompilerCompiler gccgcc MakefileMakefile makemake

DebuggingDebugging gdbgdb

Page 3: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

3

Using C/Unix/Linux at Using C/Unix/Linux at SITESITE

$ ssh linux$ ssh linux

Page 4: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

4

Vi EditorVi Editor

A screen-based editor used by Unix users An experience with vi

Starting the editor Cutting and Pasting/Deleting text Inserting New Text Moving the Cursor Within the File Moving the Cursor Around the Screen Replacing Text Searching for Text or Characters Saving and Quitting

http://www.eng.hawaii.edu/Tutor/vi.html#intro http://www.brezeale.com/technical_notes/

vim_notes.shtml

Page 5: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

5

Vi Basic CommandsVi Basic Commands mkdir <dirname> - create a directory cp <filename> <target> - copy a file rm <filename> - delete a file vi <filename> - open a file pressing the <Esc> key turns off the Insert mode :q – quit with saving :x – quit without saving :i – insert text before cursor, until <Esc> hit :a – append text before cursor, until <Esc> hit $ - move cursor to the end of the current line :w – move cursor to the beginning of next word 0 – move cursor to the start of current line :o – open and put text in a new line after the cursor y1 – copy current character Yn – copy n characters yy – copy current line p - paste characters x – delete single character under cursor dd – delete the current line u – undo the last action :w – save a file /<string> - search the string forward ?<string> - search the string backward

Page 6: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

6

AAvi vi Exercise Exercise

Create and edit Create and edit test.ctest.c file file

#include <stdio.h>#include <stdio.h>

main()main()

{{

printf(“Hello world, …\n”);printf(“Hello world, …\n”);

}}

Page 7: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

7

C programming/Unix C programming/Unix

#include <stdio.h>#include <stdio.h>

main()main()

{{

printf(“hello, wolrd…\n”);printf(“hello, wolrd…\n”);

}}

$ mkdir csi3130$ mkdir csi3130

$cd csi3130$cd csi3130

$ $ vivi test.c test.c

$$cccc test.c test.c

$$a.outa.out

Page 8: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

8

CompilerCompiler

GNU Compiler CollectionGNU Compiler Collection A compiler system produced by the GNU

Project supporting various programming languages

includes front ends for C (gcc), C++ (g++), Java (gcj), and Fortran (gFortran)

http://pages.cs.wisc.edu/~beechung/ref/gcc-intro.html

Page 9: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

9

GCCGCC Compile C code to an executableCompile C code to an executable

gcc -o <executable-name> <.c files>gcc -o <executable-name> <.c files>

Reporting all warning messagesReporting all warning messages gcc -Wall -o <executable-name> <.c files>gcc -Wall -o <executable-name> <.c files>

Page 10: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

10

GCC (Cont’d)GCC (Cont’d) An example of compiling two .c An example of compiling two .c

files into an executable programfiles into an executable program gcc -Wall -o assign1prob1 main.c list.cgcc -Wall -o assign1prob1 main.c list.c

An example of compiling two An example of compiling two files and then link them files and then link them separately separately gcc -Wall -o main.o -c main.c gcc -Wall -o main.o -c main.c gcc -Wall -o list.o -c list.c gcc -Wall -o list.o -c list.c gcc -Wall -o assign1prob1 main.o list.o gcc -Wall -o assign1prob1 main.o list.o

Page 11: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

11

Make commandMake command

makemake automates the process automates the process of compiling a programof compiling a program

MakefileMakefile $ make$ make $ make clean $ make clean

Page 12: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

12

DebuggingDebugging

gdbgdb is GNU Debugger is GNU Debugger A debugger for several languages Inspecting what the program is doing at

a certain point during execution Errors like segmentation faults may be

easier to find with the help of gdb http://ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/

html_node/gdb_toc.html

Page 13: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

13

GDBGDB

enable built-in debugging enable built-in debugging support support gcc [other flags] -g <source files> -o gcc [other flags] -g <source files> -o

<output file><output file> generating an expanded symbol generating an expanded symbol

table for use with gdb table for use with gdb Example:Example: gcc -Wall -Werror -ansi -gcc -Wall -Werror -ansi -

pedantic-errors -g prog1.c -o prog1.xpedantic-errors -g prog1.c -o prog1.x

Page 14: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

14

GDB (Cont’d)GDB (Cont’d) enter gdbenter gdb

gdbgdb enter gdbenter gdb

quitquit printing line from a source fileprinting line from a source file

listlist running a programrunning a program

runrun breakpoint at a line numberbreakpoint at a line number

break <c file name>:<line number>break <c file name>:<line number> break <line number>break <line number>

break at a particular functionbreak at a particular function break <c file name>:<functionname>break <c file name>:<functionname>

set a breakpoint with condition set a breakpoint with condition break <function or file name> if <condition>break <function or file name> if <condition>

deleting breakpointsdeleting breakpoints deletedelete

proceed onto the next breakpointproceed onto the next breakpoint continuecontinue

Single stepSingle step stepstep

Page 15: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

15

debugging exercisedebugging exercise

Reverse a stringReverse a string#include <string.h>#include <stdio.h>char * reverse(char s[]){

int c, i, j;For(i =0, j=strlen(s)-1; i< j; i++, j--){ c = s[i];S[i] =s[j];S[j]=c;}

}

Main(){

printf(“%s \n”,reverse(“database”));}

Page 16: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

16

GDB debugging GDB debugging exerciseexercise

Program failed, why???

Load the program into

GDB

Page 17: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

17

GDB debugging GDB debugging exerciseexercise

Here failed?

What is the value of i

Page 18: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

18

GDB debugging GDB debugging exerciseexercise

Try the basic GDB commands

here!

Track your program step by step, inspect the

variables..

Page 19: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

19

Correct codeCorrect code#include <string.h>#include <stdio.h>char * reverse(char s[]){ int c, i, j; for(i =0, j=strlen(s)-1; i< j; i++, j--) { c = s[i]; s[i] =s[j]; s[j]=c; }return s;}

int main(){char myStr[9]="database";printf("%s \n",reverse(myStr));return 0;}

Page 20: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

20

From Java to CFrom Java to C

Page 21: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

21

Types, Operators and Types, Operators and ExpressionsExpressions

Data typeData typechar, int, float, double, short int, long int

ConstantsConstants #define PI 3.1415926

Typedef: assigning alternative names to existingTypedef: assigning alternative names to existing typedef int myInteger;

Relational and logical operatorsRelational and logical operators> >= < <= == !=

Increment and decrement operatorsIncrement and decrement operatorsb = a++; b = ++a; b = a--; b = --a;

Page 22: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

22

Control FlowControl Flow The semicolon is a statement terminatorThe semicolon is a statement terminator

If-Else, Else-IfIf-Else, Else-Ifif (expression) if (expression) statement1 statement1else else if (expression)

statement2 statement2else statement3

For loopFor loopyou need to define the counter variable before the loop

for(expr1; expr2; expr3) statement

While-DoWhile-Doexpr1;While(expr2) statement expr3;

Do-WhileDo-Whiledo statementWhile(expression);

Page 23: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

23

Control Flow (Cont’d)Control Flow (Cont’d) SwitchSwitch

switch (expression){switch (expression){

case const-expr : statementscase const-expr : statements

case const-expr : statementscase const-expr : statements

default: statementsdefault: statements

}}

Conditional expressions Conditional expressions (expr1 ? expr2 : expr3)(expr1 ? expr2 : expr3)

if(a>b)if(a>b)

z=a;z=a; z = (a > b) ? a : b ;z = (a > b) ? a : b ;

elseelse

z=b;z=b;

Page 24: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

24

Function declarationFunction declaration

Return valueReturn value Default return value of a function in C is intDefault return value of a function in C is int

JavaJava The use of function may appear earlier than its definitionThe use of function may appear earlier than its definition

C programC program Should be Should be declareddeclared somewhere earlier than their invocations somewhere earlier than their invocations

int power(int b, int e); int power(int b, int e);

……

/* call power() here *//* call power() here */

……

int power(int b, int e) int power(int b, int e)

{{

int r = 1;int r = 1;

while (e-- > 0) r *= b; while (e-- > 0) r *= b;

return r;return r;

}}

int power(int b, int e) int power(int b, int e)

{{

int r = 1;int r = 1;

while (e-- > 0) r *= b; while (e-- > 0) r *= b;

return r;return r;

}}

main()main()

{{

......

/* call power() here *//* call power() here */

}}

Page 25: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

25

Input and OutputInput and Output printf(“the int value is %d”, var); printf(“the string value is %s”, var); printf(“the charactr and double values are %c and %e”,

var); printf(“the double value is %e”, var);

scanf(“enter an int: %d”, var); scanf(“enter a string: %s”, var); scanf(“enter a character and a double: %c %e”, var); scanf(“enter a string: %s”, var);

Do not forget including <stdio.h>

Page 26: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

26

Variable scopeVariable scope

int globalVar = 34;int globalVar = 34;

myFun()myFun()

{{

int x =1;int x =1;

}}

Global; outside of the function

Local

Page 27: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

27

Some details about CSome details about C No boolean type in CNo boolean type in C

No explicit boolean typeNo explicit boolean type                     #define TRUE 1 #define TRUE 1

#define FALSE #define FALSE             if (a){             if (a){

… … } }

No function overloading in CNo function overloading in C Two functions cannot have the same name

Variables must be declared at the top of a basic block (for Variables must be declared at the top of a basic block (for some c systems)some c systems)

The following may not pass the compiler                {    int a;{    int a;              printf("Hello world\n");              printf("Hello world\n");                            char b;char b;         }          }

Lack of exceptionsLack of exceptions Illegal activity may not be told (e.g. access memory that hasn’t been allocated in some way)

No automated garbage collection in CNo automated garbage collection in C you must free the memory

Page 28: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

28

Standard libraryStandard library <stdlib.h><stdlib.h>

dynamic memory allocationdynamic memory allocation <stdio.h><stdio.h>

Input/outputInput/output <string.h><string.h>

String handlingString handling <math.h><math.h>

Mathematical functionsMathematical functions <ctype.h><ctype.h>

CharactersCharacters

http://www.utas.edu.au/infosys/info/documentation/C/CStdLib.html

Page 29: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

29

Some common errorsSome common errors if (a=1){if (a=1){                                some stuff some stuff

            }            }        ==    Boolean evaluation

=      Variable assignment operator

void myfunc(int a) { /* ... */ } void myfunc(int a) { /* ... */ } void myfunc(float b) { /* ... */ } void myfunc(float b) { /* ... */ }

error: myfunc already defined

Page 30: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

30

ExerciseExercise Write a program that Write a program that

Accepts an input “x” (A value to progress up to) Accepts an input “x” (A value to progress up to) Starting at 0 and 1, outputs the Fibonacci Starting at 0 and 1, outputs the Fibonacci

sequence up to “x” permutations. sequence up to “x” permutations.

There should be two functions, for clarity. There should be two functions, for clarity. ((mainmain) Accepts the input and calls the fibonacci ) Accepts the input and calls the fibonacci

function. function. ((fibonaccifibonacci) One that accepts the value of x and ) One that accepts the value of x and

outputs the sequence. outputs the sequence.

Page 31: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

31

Fibonacci in JavaFibonacci in Javaimport java.ioclass Fibonacci { public static void main(String args[]) {

System.out.println("How many numbers of the sequence would you like?"); InputStreamReader sr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(sr); try {

String input = br.readLine(); int n = Integer.valueOf(input).intValue(); fibonacci(n);

} catch (NumberFormatException e){System.out.println("That is not an integer. Please enter an integer value"); } catch (IOException e) { System.out.println("I did not recieve an input"); }

} public static void fibonacci(int n){

int a=0,b=1; for (int i=0;i<n;i++){

System.out.println(a); a=a+b; b=a-b;

} }}

Page 32: Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

32

Fibonacci in CFibonacci in C

#include <stdio.h> int main () {

int n; printf("\nHow many numbers of the sequence would you like?\n"); scanf("%d",&n); fibonacci(n); return 0;

} int fibonacci(int n) {

int a = 0; int b = 1; int sum; int i; for (i=0;i<n;i++) {

printf("%d\n",a); sum = a + b; a = b; b = sum;

} return 0;

}