a guide to unix using linux fourth edition chapter 10 developing unix/linux applications in c and...

42
A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

Upload: hannah-bradford

Post on 12-Jan-2016

234 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux Fourth Edition

Chapter 10Developing UNIX/Linux Applications in

C and C++

Page 2: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 2

Objectives

• 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

Page 3: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 3

Objectives (continued)

• Identify differences between C and C++ programming

• Create a simple C++ program

• Create a C++ program that reads a text file

• Create a C++ program that demonstrates how C++ enhances C functions

Page 4: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 4

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

Page 5: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 5

Creating a C Program

Page 6: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 6

C Keywords

• Keywords have special meanings– Cannot be used as names for variables or functions

Page 7: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 7

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– Other tasks: functions to perform string operations,

memory allocation, control, etc.

• 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

Page 8: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 8

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()

{

}

Page 9: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 9

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()

{

}

Page 10: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 10

Using the Preprocessor #include Directive

• The following program creates output:/* A simple C program */

#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 preprocessor directive

Page 11: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 11

Using the Preprocessor #include Directive (continued)

Page 12: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 12

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

Page 13: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 13

Specifying Data Types (continued)

Page 14: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 14

Character Constants

• Characters are represented internally in a single byte of the computer’s memory– Stored according to the character’s code in the host

character set• 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’

Page 15: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 15

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

Page 16: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 16

Including Identifiers

• 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

Page 17: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 17

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;

Page 18: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 18

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;int main(){}

A global or external variable

Page 19: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 19

Using Math Operators

• Example:x = y + 3;

• Increment and decrement operators are unary– Examples: count--; or x = ++j;

Page 20: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 20

Generating Formatted Output with printf()

• 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);

Page 21: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 21

Generating Formatted Output with printf() (continued)

Page 22: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 22

Using the C Compiler

Page 23: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 23

Using the if Statement

• Example:if (weight > 1000)

{

printf("Warning!\n");

printf("You have exceeded the limit.\n");

printf("Please remove some weight.\n");

}

Page 24: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 24

Using the if Statement (continued)

• 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!");

Page 25: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 25

Using C Loops

• Three looping mechanisms in C:– for loop

for (count = 0; count < 100; count++) printf("Hello\n");

– while loopx = 0;while (x++ < 100) printf("x is equal to %d\n", x);

– do-while loopx = 0;do printf("x is equal to %d\n", x);while (x++ < 100);

Page 26: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 26

Defining Functions

• To define a function, declare its name and create the function’s block of code

#include <stdio.h>void message();int main(){ message();}void message(){ printf("Greetings from the function message."); printf("Have a nice day.");}

[stephen@localhost ~] $ ./func1Greetings from the function message.Have a nice day.

Function prototype

This function does not return a value

Page 27: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 27

Using Function 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

Page 28: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 28

Using Function 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 ~]$ ./func36 tripled is 18.

Page 29: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 29

Working with Files in C

• C file input/output is designed to use file pointersFILE *fp;

• Before you can use a file, it must be openedif ((fp = fopen("myfile.dat", "r")) == NULL){

printf("Error opening myfile.dat\n");}

• When a file is closed, its buffers are flushedif (feof(fp))

fclose(fp);

• C provides many functions for reading/writing filesch = fgetc(fp);fputc(ch, fp);

Page 30: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 30

Using the make Utility 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

Page 31: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 31

Using the make Utility to Maintain Program Source Files (continued)

• Example of a makefile:abs_main.o: abs_main.c gcc -c abs_main.cabs_func.o: abs_func.c gcc -c abs_func.cabs2: abs_main.o abs_func.o gcc abs_main.o abs_func.o -o abs2

Page 32: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 32

Using the make Utility to Maintain Program Source Files (continued)

Page 33: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 33

Debugging Your Program

• Typical errors for new C programmers include using incorrect syntax– Example: forgetting to terminate a statement with a

semicolon (;)

• Example of a compiler error output:simple.c:10: unterminated string or character constantsimple.c:10: possible real start of unterminated

constantsimple.c:4:10: missing terminating " charactersimple.c:5: error: syntax error before ’}’ token

• Compiler generally produces more error lines than the number of mistakes it finds in the code

Page 34: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 34

Debugging Your Program (continued)

• 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

– Within the source file, correct the error• Then, continue with the next line number

– After correcting errors, save and recompile

Page 35: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 35

Creating a C Program to Accept Input

Page 36: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 36

Creating a C Program to Accept Input (continued)

• Examples:scanf("%d", &age);

scanf("%s", city);

scanf("%d %f %d", &x, &y, &z);

Page 37: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 37

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

Page 38: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 38

Creating 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";}

Page 39: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 39

Creating 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; } }}

Page 40: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 40

How C++ Enhances C Functions//======================================================// 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);}

Page 41: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 41

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

Page 42: A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

A Guide to Unix Using Linux, Fourth Edition 42

Command Summary