introduc)on to the c programming language · 2018. 1. 24. · introduc)on to the c programming...

49
Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scien)fic Compu)ng Winter semester 2015/2016 Konstan)nos Chasapis Konstan)nos.chasapis@informa)k.uni-hamburg.de

Upload: others

Post on 19-Jan-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Introduc)ontotheCprogrammingLanguage

Prak)kumKernelProgrammingUniversityofHamburgScien)ficCompu)ng

Wintersemester2015/2016

Konstan)nosChasapisKonstan)nos.chasapis@informa)k.uni-hamburg.de

Page 2: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Outline

•  HelloWorld•  Preprocessor/Compiler/Linker•  Thebasis•  Pointers•  MemoryLayout/alloca)on•  Structures/unions•  Inlineassembly

Introduction to C 21/10/15 1

Page 3: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

HelloWorld•  Preprocessor

–  cpp–  #include<stdio.h>

•  mainfunc)on– Getstwoarguments

•  argc,the#ofcommandlinearguments•  argv,stringsofthecommandlinearguments

–  Returnsanintegertodenotetheexecu)onstatus•  0insuccessfullexecu)on

•  PrinV–  Printstothestandardoutput

Introduction to C

#include<stdio.h>intmain(intargc,char*arv[]){printf("Helloworld!\n");return0;}

21/10/15 2

Page 4: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Preprocessor(cpp)•  Executesbeforethecompila)on•  Includeheaderfiles

–  #include<filename.h>–  <>-searchinstandarddirectories–  “”pathtothefile

•  Macrosexpansion–  #defineEXTVALUE–  #undefEXT

•  Condi)onalCompila)on–  #if,#elif,#endif–  #ifdef,#ifndef

Introduction to C 21/10/15 3

Page 5: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Preprocessor(cpp)

•  Otherdirec)ves– #Replacesamacroparameterwithastringconstant

– ##Tokenmerge,createsasingletokenfromtwoadjacentones

•  Macroscon)nua)on(\)– #defineLONG_MACRO\

Expand_also_here

Introduction to C 21/10/15 4

Page 6: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Preprocessor(cpp)

•  Usefulpredefinedmacros__DATE__

•  Currentdateasastringwith"MMMDDYYYY”format__TIME__

•  Current)measstringwith"HH:MM:SS“format__FILE__

•  Currentfilenameasastring__LINE__

•  Currentlinenumberasanumber

•  hops://gcc.gnu.org/onlinedocs/cpp/

Introduction to C 21/10/15 5

Page 7: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Compile•  Manyopensourcecompilers•  gcc(GNUCompilerCollec)on)

-c,createsanobjectfile•  $filename.o

-o,nametheexecutable•  defaultnamea.out

-g,adddebugginginforma)on-Wall,enablesallwarnings

•  gcc-ohello_worldhello_world.c•  hop://pages.cs.wisc.edu/~beechung/ref/gcc-intro.html

Introduction to C 21/10/15 6

Page 8: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Createtheexecutable•  Cpreprocessor

–  Passpreprocessordirec)ves•  Compila)on

–  Csourcecodeintoassemblycode–  Checkforsyntaxerrors

•  Assembling– Assemblysourcecodeintoassemblylis)ngwithoffsets

•  Linking–  Takesoneormanyobjectfilesandlibrariestocreateasingleexecutable

source code.c

source code.i

source code.s

source code.o

executable

Introduction to C 21/10/15 7

Page 9: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Outline

•  HelloWorld•  Preprocessor/Compiler/Linker•  Thebasis•  Pointers•  MemoryLayout/alloca)on•  Structures/unions•  Inlineassembly

Introduction to C 21/10/15 8

Page 10: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Iden)fiersnames

•  Usetoiden)fy– Variablenames– Func)onnames– Otheruser-defineditems

•  Format– StartswithA-Z,a-z– Followedbyleoers,digits,underscores_– Casesensi)ve

Introduction to C 21/10/15 9

Page 11: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Variablesbasicdatatypes•  int,integers

–  signed–  unsigned–  short–  longlong–  char,characters

•  signedchar,-128..127•  unsignedchar,0..256

•  floa)ngpoint(IEE754standard)–  float,singledprecision–  double,doubleprecision

Introduction to C 21/10/15 10

Page 12: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

voidtype•  Mul)plemeanings•  Whenusedinfunc)onargumentlist

–  funct(void)– Doesnotacceptanyargument

•  Returnvalueofafunc)on–  voidfucnt(..)– Doesnotreturnanyvalue

•  Pointertoavalue–  void*v_pointer;–  pointstounspeciateddatatype

Introduction to C 21/10/15 11

Page 13: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Variablesqualifiers

•  Const– Variablecannotchangeazerini)aliza)on– constfloatpi=3.14;

•  Vola)le– Extremeoppositeofconst.–  Indicatesthatavariablemaybechangedinaway– Everyreferencetothevariablewillreloadthecontentsfrommemory

– vola)leintv;

Introduction to C 21/10/15 12

Page 14: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

enumdatatype

•  Abbrevia)onforenumerate•  Declareandini)alizeasequenceofintegerconstants

•  Example:– enumcolors{RED,YELLOW,GREEN};– enumcolors{RED=0,YELLOW=1,GREEN=2};

Introduction to C 21/10/15 13

Page 15: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

VariableStorageClass•  auto

–  Defaultforstoringthelocalvariables•  register

–  LocalvariablesthatshouldbestoredinregistersinsteadofRAM

–  fastaccess•  sta)c,twomeanings

–  Globalvariables,canbeseeninthisfileonly.–  Localvariables,ini)alizedonce,retainsvalueduringvariouscalls

•  extern– Makeaglobalvariablevisibletoallprogramfiles

Introduction to C 21/10/15 14

Page 16: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Variablessize-sizeof()

•  Specialoperatorreturnsthesizeinchar•  Examples

– sizeof(char)//1– sizeof(int)//4– sizeof(float)//4– sizeof(double)//8

Introduction to C 21/10/15 15

Page 17: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Arrays

•  Madefromelementsofbasictypes•  Usesquarebrackets[]todeclarethem•  Canhavemul)pledimensions•  Cannotchangesizeduringexecu)on)me•  Allocatedsequen)ally•  Startfrom0•  Examples

–  inta[3]={1,2,3};–  charstrings[2][5]={“this”,“is”,“test”};

Introduction to C 21/10/15 16

Page 18: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Strings

•  Specialcaseofchararrays•  Nullterminated•  Example:

– charstring[5];•  string[0]=`t`;•  string[1]=`e`;•  string[2]=`s`;•  string[3]=`t`;•  String[4]=`\0`;

Introduction to C 21/10/15 17

Page 19: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Variablescope•  Global

–  Definedoutsideofablock/func)on–  Canbeaccessedbyanyfunc)on/block–  Retainvalueduringtheprogramexecu)on

•  Local–  Definedinsideablock(compoundstatement)–  Mainlyinthetopofthefunc)on/block–  Usedonlyinthisblock–  Overwritesglobalvariableswiththesamename–  Losevalueattheendofthefunc)on/block

•  Formal–  Func)onparameters,usedaslocalvariables

Introduction to C 21/10/15 18

Page 20: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Constants•  Numericvalues

– Octalstartswith0,015– Hexadecimalstartswith0x,0xA1–  LongendswithL,12312341124L

•  Characters–  \n, newline–  \t, tab–  \\, backslash–  \’’, singlequote–  \0, stringterminatecharacter– NULL,integervalueof0

Introduction to C 21/10/15 19

Page 21: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Operators•  Arithme)cOperators

–  +,-,*,/,%,++,--•  LogicalOperators

–  ==,!=,<=,<,>=,>,!,&&,||•  BitwiseOperators

– &,|,^,~,<<,>>•  AssignmentOperators

–  =,+=,-=,*=,/=,%=,&=,^=,|=•  MiscOperators

–  sizeof(),&,*,?=

Introduction to C 21/10/15 20

Page 22: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Statements

•  Expressionstatements–  Expressionfollowedbysemicolon;

•  a=1+3;•  Compoundstatements

– Oneormorestatementsenclosedbyapairofbraces{}

•  {pi=3.14;area=pi*radios*radios;}•  Controlstatements

–  Controltheexecu)onflow•  if,else,case,foretc.

Introduction to C 21/10/15 21

Page 23: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Condi)onalstatementsContrac)on

•  if(expression)statement;–  ifexpressionevaluatedasnonzeroenterstheifstatement

•  Exampleif(a<X){code_block}elseif(a>X){code_block}else{code_block}

Introduction to C 21/10/15 22

Page 24: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Condi)onalstatementsContrac)on

switch(expression){caseconstant-expr1:statement1;[caseconstant-expr2:statement2;]default:statement3;

}•  Firstevaluatesexpression•  Thenentersthecasethatmatchestheexpressionvalues•  Otherwiseexecutesthedefault•  Con)nuestheexecu)onun)litfindsbreak;

Introduction to C 21/10/15 23

Page 25: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Condi)onalstatementsContrac)on

•  Checkifvariable“a”isequaltoXorYorZ

switch(a){ caseX:{codeblock} caseY:{codeblock} caseZ:{codeblock} default: //noteqaultoX,Y,Z}

Introduction to C 21/10/15 24

Page 26: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Looping-for

•  for(expr1;expr2;expr3){compoundstatements}–  Executestheexpr1inthebeginning–  Evaluatestheexpr2andifnonzeroexecutesthecompoundstatements

– Attheendexecutestheexpr3andreevaluatestheexpr2con)nuesun)lexpr2iszero.

•  Examplefor(i=0;i<ARRAYSIZE;i++){ codeblock;}

Introduction to C 21/10/15 25

Page 27: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Looping-while

•  while(expression){compoundstatements}– Evaluatesexpressionandifnonzeroexecutesthecompoundstatementsun)lexpressionisnonzero

•  Examplei=0;while(i<ARRAYSIZE){ codeblock; i++;}

Introduction to C 21/10/15 26

Page 28: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Looping–dowhile

•  do{compoundstatements}while(expression);

– Executesthecompoundstatements– Evaluatestheexpressionandifnonzerorepeats

•  Exampledo{ i++;}while(i<ARRAY_SIZE);

Introduction to C 21/10/15 27

Page 29: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

breakandcon)nue

while(i<10){i=i+1;if(i<10)con)nue; i=0;break;

}

• break– Exitsalooporacasestatement

• con)nue– Con)nuestheexecu)onfromthebeginningoftheloop

switch(a){caseZ:{codeblock

break;}caseY:{codeblock}caseX:{codeblock}

}

Introduction to C 21/10/15 28

Page 30: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Commnets

•  Singlelinecomments– //comments

•  Mul)plelinescomments– /*comments*/

Introduction to C 21/10/15 29

Page 31: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Func)ons•  Madeupbyfourcomponents

–  Returnvalue–  Func)onname–  Argumentslist–  Func)onbody

•  Example–  intfunc)on_name(inta,intb){returna+b;}

•  Parameters–  Callbyvalue,copiesthevalueoftheargumenttotheformalparameter

–  Callbyreference,copiestheaddressoftheargumenttoformalparameter

Introduction to C 21/10/15 30

Page 32: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Func)onsexamples

•  Returnsanintegergetsnoargument–  intfoo(void);

•  Returnsthesumoftwofloats– floatfloat_sum(floata,floatb){returna+b;}

Introduction to C 21/10/15 31

Page 33: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Outline

•  HelloWorld•  Preprocessor/Compiler/Linker•  Thebasis•  Pointers•  MemoryLayout/alloca)on•  Structures/unions•  Inlineassembly

Introduction to C 21/10/15 32

Page 34: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Pointers•  Variablestoreaddresses

–  variableaddresses–  func)ons

•  Declara)on–  type*name;//variable–  type(*f_name)(..);//func)onpointer

•  Examples–  int*p_i;//pointertoanint–  double*p_d;//pointertodouble–  void(*p_f)(int);//func)onpointertoafunc)onthatreturnsvoidandhasanintegerparameter

Introduction to C 21/10/15 33

Page 35: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Pointerscont.

•  Dereference– Getthevalueofthevariablepointerpointsto– Use(*)

•  Addressofavariable– Use(&)

•  Exampleinta=1;int*p_a=&a; 0x 111077AB

1 0x 111077AB a

p_a

Introduction to C 21/10/15 34

Page 36: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Pointerstypecas)ng

•  Convertavariablefromonetypetoanother•  Usedtocastvoid*•  Examples void*v;int*a; v=(void*)a; a=(int*)v;

Introduction to C 21/10/15 35

Page 37: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Pointersexample•  Func)onthatwillswapthevalueoftwointegervariablesvoidswap(int*a,int*b){ inttmp; tmp=*a;//storethevaluethatapointstoattmp *a=*b; *b=tmp;}

•  Howtocallthefunc)oninta=3,b=4;swap(&a,&b);

Introduction to C 21/10/15 36

Page 38: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

MemoryLayout•  textsegment

–  Sourcecode•  datasegment

– Globalvariables–  Sta)cvariables

•  heap–  Dynamicallyallocatedmemory

•  stack–  Localvariables–  Func)onparameters

text segment

data segment

heap

unallocated

stack

low address

high address Introduction to C 21/10/15 37

Page 39: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Stackalloca)on•  stackpointer(sp)

–  topofthestack

g(){;}

f(){g();

}

main(){f();

}main() main()

f()

sp

sp

sp

params

main()

f() params

params g()

Introduction to C 21/10/15 38

Page 40: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Heapalloca)on

•  Stackallocatessta)csizevariables– Sizeknowedatcompile)me

•  Dynamicallymemorystoredinheap•  Allocateusing

– malloc()//allocatesrequestedamount– calloc()//allocatesandzerosmemory

•  Youhavetoexplicitlyfreethememory– Doesnothavegarbagecollec)on–  free()

Introduction to C 21/10/15 39

Page 41: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Heapalloca)onExamples

•  Allocateanarrayof10integersint*a;a=(int*)malloc(10*sizeof(int));free(a);

•  Allocateanarrayof10floatsandzerothemfloat*a;a=(float*)calloc(10,sizeof(float));free(a);

Introduction to C 21/10/15 40

Page 42: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Outline

•  HelloWorld•  Preprocessor/Compiler/Linker•  Thebasis•  Pointers•  MemoryLayout/alloca)on•  Structures/unions•  Inlineassembly

Introduction to C 21/10/15 41

Page 43: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Structures•  Collec)onofitemsofdifferenttypes

–  Itemscalledmembers/fields•  SimilartoClassesofJava•  Example structperson{

charname[255]; intheight;}

•  Accessstructmembers–  Forreference/pointertoastructuse->

•  structperson*p_person;p_person->height;–  Fortheactualstructuse.

•  structpersonperson;person.height;

Introduction to C 21/10/15 42

Page 44: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Unions•  Storedifferentdatatypeinasinglememoryloca)on

•  Similardefini)onsofstructs•  Example

unionData{inti;floatf;charstr[20];}

•  Accessfieldsusing.– Data.i=3;

Introduction to C 21/10/15 43

Page 45: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Typedef

•  Nameanewtype•  Mainlyusedforstructbutnotlimited•  Syntax

–  typedeftypetype_name

•  Examples–  typedefunsignedcharBYTE;–  typedefstructpersonperson_t;

Introduction to C 21/10/15 44

Page 46: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Inlineassembly•  asm-gccextension

–  ReadandwriteCvariablesfromassembler–  PerformjumpsfromassemblercodetoClabels–  Foransiandstduse_asm_

•  Basicsyntax–  asm[vola)le](AssemblerInstruc)ons)–  Addmul)pleassemblylineswith‘\n\t’

•  Extendedasmsyntax–  asm[vola)le](AssemblerTemplate:OutputOperands[:InputOperands[:Clobbers]])

Introduction to C 21/10/15 45

Page 47: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

asmexamples

•  Copysrctodstandadd1todst– asm("mov%1,%0\n\t""add$1,%0":"=r"(dst):"r"(src));

Introduction to C 21/10/15 46

Page 48: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Keywords

externreturnunioncharfloatshortunsignedconstfor

signedvoidcon)nuegotosizeofvola)ledefaultifsta)c

whiledointstructdouble

Introduction to C

autoelselongswitchbreakenumregistertypedefcase21/10/15 47

Page 49: Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming Language Prak)kum Kernel Programming University of Hamburg Scienfic Compung Winter

Ques)ons?

Konstan)nosChasapis

Konstan)nos.chasapis@informa)k.uni-hamburg.de

Introduction to C 21/10/15 48