Chapter  10   Developing  UNIX/Linux  Applications  in  C   and  C++  

Objec&ves  
  Understand  basic  elements  of  C  programming     Debug  C  programs     Create,  compile,  and  test  C  programs     Use  the  make  utility  to  revise  and  maintain  source  

files  

A Guide to Unix Using Linux, Fourth Edition

2

Objec&ves  (con&nued)  
  Create  a  simple  C++  program  

  Identify  differences  between  C  and  C++  programming     Create  a  C++  program  that  reads  a  text  file     Create  a  C++  program  that  demonstrates  how  C++  

enhances  C  functions  

A Guide to Unix Using Linux, Fourth Edition

3

Introducing  C  Programming  
  Unix  was  developed  and  refined  in  the  C  language       Original  UNIX  OS  was  written  in  assembly  language  
 

Assembly  language:  low-­‐level  language;  provides  maximum   access  to  all  the  computer’s  devices  

  Ritchie  and  Kernighan  from  AT&T  Bell  Labs  rewrote  

most  of  UNIX  using  C  in  early  1970s  

  C  is  native  to  UNIX/Linux     Works  best  as  an  application  development  tool  
 

Example:  daemons  are  written  in  C  

  C  is  a  compiled  language  
A Guide to Unix Using Linux, Fourth Edition 4

Crea&ng  a  C  Program  

A Guide to Unix Using Linux, Fourth Edition

5

C  Keywords  
  Keywords  have  special  meanings     Cannot  be  used  as  names  for  variables  or  functions  

A Guide to Unix Using Linux, Fourth Edition

6

The  C  Library  
  The  C  language  is  very  small     No  input  or  output  facilities     All  I/O  is  performed  through  the  C  library     C  library:  consists  of  functions  that  perform  file,  

screen,  and  keyboard  operations  
memory  allocation,  control,  etc.  

  Other  tasks:  functions  to  perform  string  operations,  

  To  perform  one  of  these  operations  in  program,  place  

a  function  call  

  Linker  joins  code  of  library  function  with  program’s  

object  code  to  create  executable  file  
A Guide to Unix Using Linux, Fourth Edition

7

Program  Format  
  C  programs  are  made  up  of  one  or  more  functions     Every  function  must  have  a  name     Every  C  program  must  have  a  main()  function:  
int main() { }

A Guide to Unix Using Linux, Fourth Edition

8

Including  Comments  
  /*  denotes  the  beginning  of  a  comment     */  denotes  the  end  of  a  comment     Compiler  ignores  everything  between  the  symbols:
/* Here is a program that does nothing. */ int main() { }

A Guide to Unix Using Linux, Fourth Edition

9

Using  the  Preprocessor  #include   Direc&ve  
  The  following  program  creates  output:  
/* A simple C program */ A preprocessor directive #include <stdio.h> int main() { printf("C is a programming language.\n"); printf("C is very compatible with UNIX/Linux.\n"); }

  stdio.h  is  a  header  file  

A Guide to Unix Using Linux, Fourth Edition

10

Using  the  Preprocessor  #include   Direc&ve  (con&nued)  

A Guide to Unix Using Linux, Fourth Edition

11

Specifying  Data  Types  
  Variables  and  constants  represent  data  used  in  a  C  

program     You  must  declare  variables  and  state  type  of  data  that   variable  can  hold     A  variable’s  data  type  determines  upper  and  lower   limits  of  its  range  of  values  
  Exact  limits  of  ranges  vary  among  compilers  and  

hardware  platforms  

A Guide to Unix Using Linux, Fourth Edition

12

Specifying  Data  Types  (con&nued)  

A Guide to Unix Using Linux, Fourth Edition

13

Character  Constants  
  Characters  are  represented  internally  in  a  single  byte  

of  the  computer’s  memory  
character  set  
 

  Stored  according  to  the  character’s  code  in  the  host  

Example:  if  machine  uses  ASCII  codes,  letter  A  is  stored  in   memory  as  the  number  65  

  In  a  program,  a  character  constant  must  be  enclosed  

in  single  quotation  marks  
‒  ‘A’ ‒  ‘c’
A Guide to Unix Using Linux, Fourth Edition 14

Using  Strings  
  A  string  is  a  group  of  characters,  such  as  a  name     Strings  are  stored  in  memory  in  consecutive  memory  

locations     String  constants  are  enclosed  in  double  quotation   marks  
‒  "Linux is a great operating system."

  C  does  not  provide  a  data  type  for  character  strings     Use  a  character  array  instead:  char name[20];
 

Can  hold  a  string  of  19  characters,  terminated  with  the  null   character  
A Guide to Unix Using Linux, Fourth Edition 15

Including  Iden&fiers  
  Identifiers  are  names  given  to  variables  and  

functions  

  First  character  must  be  a  letter  or  an  underscore     For  other  characters,  use  letters,  underscores,  or  digits     Variable  names  can  be  limited  to  31  characters     Some  compilers  require  first  eight  characters  to  be  unique     Uppercase  and  lowercase  characters  are  distinct  

  Tip:  use  meaningful  identifiers     Examples:  radius,  customer_name,  my_name  

A Guide to Unix Using Linux, Fourth Edition

16

Declaring  Variables  
  You  must  declare  all  variables  before  you  use  them  in  

a  program  

int days;

  You  can  declare  multiple  variables  of  the  same  type  

on  the  same  line  

int days, months, years;

  You  can  initialize  variables  with  values  at  the  time  

they  are  declared  
int days = 5, months = 2, years = 10;

A Guide to Unix Using Linux, Fourth Edition

17

Understanding  the  Scope  of   Variables  
  Scope  of  a  variable:  part  of  the  program  in  which  the  

variable  is  defined  and  accessible  

/* This program declares a local variable in function main. The program does nothing else. */ int main() { int days; An automatic variable } /* This program declares a global variable The program does nothing else. */ int days; A global or external variable int main() { }
A Guide to Unix Using Linux, Fourth Edition 18

Using  Math  Operators  

  Example:  
x = y + 3;

  Increment  and  decrement  operators  are  unary     Examples:  count--;  or  x = ++j;
A Guide to Unix Using Linux, Fourth Edition 19

Genera&ng  FormaKed  Output  with   prinL()  

  Examples:  
printf("Hello"); printf("Your age is %d", 30); printf("Your age is %d", age); printf("The values are %d %d", num1, num2); printf("You have worked %d minutes", hours*60);
A Guide to Unix Using Linux, Fourth Edition 20

Genera&ng  FormaKed  Output  with   prinL()  (con&nued)  

A Guide to Unix Using Linux, Fourth Edition

21

Using  the  C  Compiler  

A Guide to Unix Using Linux, Fourth Edition

22

Using  the  if  Statement  

  Example:  
if (weight > 1000) { printf("Warning!\n"); printf("You have exceeded the limit.\n"); printf("Please remove some weight.\n"); }
A Guide to Unix Using Linux, Fourth Edition 23

Using  the  if  Statement  (con&nued)  
  if-­‐else  construct  allows  program  to  do  one  thing  if  a  

condition  is  true  and  another  if  it  is  false       Example:  
if (hours > 40) printf("You can go home now."); else printf("Keep working!");

A Guide to Unix Using Linux, Fourth Edition

24

Using  C  Loops  
  Three  looping  mechanisms  in  C:     for  loop  
for (count = 0; count < 100; count++) printf("Hello\n");

  while  loop   x = 0; while (x++ < 100) printf("x is equal to %d\n", x);   do-­‐while  loop   x = 0; do printf("x is equal to %d\n", x); while (x++ < 100);
A Guide to Unix Using Linux, Fourth Edition 25

Defining  Func&ons  
  To  define  a  function,  declare  its  name  and  create  the  

function’s  block  of  code  

#include <stdio.h> void message(); Function prototype int main() { message(); This function does not return a value } void message() { printf("Greetings from the function message."); printf("Have a nice day."); } [stephen@localhost ~] $ ./func1 Greetings from the function message. Have a nice day.
A Guide to Unix Using Linux, Fourth Edition 26

Using  Func&on  Arguments  
  Argument:  a  value  passed  to  a  function     Stored  in  special  automatic  variables  
#include <stdio.h> void print_square(int val) main() { int num = 5; print_square(num); } void print_square(int val) { printf("\nThe square is %d\n", val*val); } [stephen@localhost ~]$ ./func2 The square is 25
A Guide to Unix Using Linux, Fourth Edition 27

Using  Func&on  Return  Values  
#include <stdio.h> int triple(int num); int main() { int x = 6, y; y = triple(x); printf("%d tripled is %d.\n", x, y); } int triple(int num) { return (num * 3); } [stephen@localhost ~]$ ./func3 6 tripled is 18.

A Guide to Unix Using Linux, Fourth Edition

28

Working  with  Files  in  C  
  C  file  input/output  is  designed  to  use  file  pointers  
FILE *fp;

  Before  you  can  use  a  file,  it  must  be  opened  

if ((fp = fopen("myfile.dat", "r")) == NULL) { printf("Error opening myfile.dat\n"); } if (feof(fp)) fclose(fp);

  When  a  file  is  closed,  its  buffers  are  flushed     C  provides  many  functions  for  reading/writing  files  
ch = fgetc(fp); fputc(ch, fp);
A Guide to Unix Using Linux, Fourth Edition 29

Using  the  make  U&lity  to  Maintain   Program  Source  Files  
  You  might  often  work  with  a  program  that  has  many  

files  of  source  code  

  Advantage:  break  down  code  into  smaller  modules  that  

can  be  reused     Problem:  avoid  recompiling  all  files  if  only  one  changed  

  make  utility  tracks  what  needs  to  be  recompiled  by  

using  a  time  stamp  field  for  each  source  file  
  Must  create  a  control  file  called  makefile  
 

Must  exist  in  current  directory  

A Guide to Unix Using Linux, Fourth Edition

30

Using  the  make  U&lity  to  Maintain   Program  Source  Files  (con&nued)  

  Example  of  a  makefile:  
abs_main.o: abs_main.c gcc -c abs_main.c abs_func.o: abs_func.c gcc -c abs_func.c abs2: abs_main.o abs_func.o gcc abs_main.o abs_func.o -o abs2
A Guide to Unix Using Linux, Fourth Edition 31

Using  the  make  U&lity  to  Maintain   Program  Source  Files  (con&nued)  

A Guide to Unix Using Linux, Fourth Edition

32

Debugging  Your  Program  
  Typical  errors  for  new  C  programmers  include  using  

incorrect  syntax  
semicolon  (;)  

  Example:  forgetting  to  terminate  a  statement  with  a  

  Example  of  a  compiler  error  output:  
simple.c:10: unterminated string or character constant simple.c:10: possible real start of unterminated constant simple.c:4:10: missing terminating " character simple.c:5: error: syntax error before ’}’ token

  Compiler  generally  produces  more  error  lines  than    

the  number  of  mistakes  it  finds  in  the  code  
A Guide to Unix Using Linux, Fourth Edition

33

Debugging  Your  Program   (con&nued)  
  Steps  to  correct  syntax  errors  within  your  programs:     Write  down  the  line  number  of  each  error  and  a  brief   description     Edit  your  source  file  
 

Start  with  the  first  line  number  the  compiler  reports   Then,  continue  with  the  next  line  number  

  Within  the  source  file,  correct  the  error  
 

  After  correcting  errors,  save  and  recompile  

A Guide to Unix Using Linux, Fourth Edition

34

Crea&ng  a  C  Program  to  Accept   Input  

A Guide to Unix Using Linux, Fourth Edition

35

Crea&ng  a  C  Program  to  Accept   Input  (con&nued)  

  Examples:  
scanf("%d", &age); scanf("%s", city); scanf("%d %f %d", &x, &y, &z);

A Guide to Unix Using Linux, Fourth Edition

36

Introducing  C++  Programming  
  C++  is  a  programming  language  developed  by  Bjarne  

Stroustrup  at  AT&T  Bell  Labs  

  Adds  object-­‐oriented  programming  capabilities     Object-­‐oriented  programming  uses  objects  for  handling   data     C++  programs  introduce  objects  as  a  new  data  class     Object:  collection  of  data  and  methods,  which  manipulate   the  data     Function  overloading  is  an  additional  useful  feature     Compiler:  g++     Example:  g++  myprogram.C  -­‐o  myprogram     Typical  file  extensions:  .C  or  .cpp  
A Guide to Unix Using Linux, Fourth Edition 37

Crea&ng  a  Simple  C++  Program  
// ====================================================== // Program Name: simple.C // By: MP // Purpose: First program in C++ showing how to // produce output // ====================================================== #include <iostream> using namespace std; int main(void) { cout << "C++ is a programming language.\n"; cout << "Like C, C++ is compatible with UNIX/Linux. \n"; }
A Guide to Unix Using Linux, Fourth Edition 38

Crea&ng  a  C++  Program  that  Reads   a  Text  File  
// ===================================================== = // Program Name: fileread.C // By: MP // Purpose: C++ program that reads contents of a file // ===================================================== = #include <iostream> #include <fstream> using namespace std; int main(void) { ifstream file("testfile"); char record_in[256]; if (file.fail()) cout << "Error opening file.\n"; else { while (!file.eof()) { file.getline(record_in, sizeof(record_in)); if (file.good()) cout << record_in << endl; } } } A Guide to Unix Using Linux, Fourth Edition

39

How  C++  Enhances  C  Func&ons  
//====================================================== // Program Name: datestuf.C // By: MP // Purpose: Shows you two ways to access the // system date //====================================================== #include <iostream> #include <ctime> using namespace std; void display_time(const struct tm *tim) { cout << "1. It is now " << asctime(tim); } void display_time(const time_t *tim) { cout << "2. It is now " << ctime(tim); } int main(void) { time_t tim = time(NULL); struct tm *ltim = localtime(&tim); display_time(ltim); display_time(&tim); }

A Guide to Unix Using Linux, Fourth Edition

40

Summary  
  C  program  modules  are  compiled  separately  into  object  

code  and  linked  to  make  up  a  program     C  programs  first  execute  instructions  in  main()     make  is  used  to  maintain  an  application’s  source  files     C  follows  procedural  principles,  while  C++  primarily   follows  object-­‐oriented  programming  principles     The  standard  stream  library  used  by  C++  is  iostream     C++  provides  two  statements  for  standard  input  and   standard  output:  cin  and  cout,  respectively     Function  overloading  allows  functions  to  handle     multiple  sets  of  criteria  
A Guide to Unix Using Linux, Fourth Edition

41

Command  Summary  

A Guide to Unix Using Linux, Fourth Edition

42

Sign up to vote on this title
UsefulNot useful