part one the essence of unix. 2 overview unix history –origins, versions, distributions using unix...
TRANSCRIPT
Part OnePart One
The Essence of UNIXThe Essence of UNIX
22
OverviewOverview
Unix historyUnix history– Origins, versions, distributionsOrigins, versions, distributions
Using UnixUsing Unix– Log in/outLog in/out
Unix shellsUnix shells
Basic commandsBasic commands
Editor(s)Editor(s)
Compile a C/C++ programCompile a C/C++ program
33
Introducing the UNIXIntroducing the UNIXOperating SystemOperating System
UNIX is a multi-user systemUNIX is a multi-user system– Allows many users access and share the Allows many users access and share the
resources of a server computerresources of a server computer
UNIX is a multitasking systemUNIX is a multitasking system– Allows user to execute more than one Allows user to execute more than one
program at a timeprogram at a time
UNIX is a portable operating systemUNIX is a portable operating system– Used in many computing environmentsUsed in many computing environments
44
Unix HistoryUnix History
Bell Labs …Bell Labs …
UC Berkeley …UC Berkeley …
Commercial versions:Commercial versions:– Solaris, Irix, HP/UX, Ultrix, SCO Unix, AIX, …Solaris, Irix, HP/UX, Ultrix, SCO Unix, AIX, …
Open source versions:Open source versions:– FreeBSDFreeBSD– LinuxLinux
55
Linux and UNIXLinux and UNIX
Linux is UNIX-likeLinux is UNIX-like– Created by Linus TorvaldsCreated by Linus Torvalds– Not written from traditional UNIX codeNot written from traditional UNIX code
Linux is original codeLinux is original code– follows POSIX standardsfollows POSIX standards
66
Linux StructureLinux Structure
77
Linux DistributionsLinux Distributions
Many companies have createdMany companies have created Linux distributionsLinux distributions
distributions contain distributions contain – source code for the Linux kernel and utilitiessource code for the Linux kernel and utilities– installation toolsinstallation tools– professional documentationprofessional documentation– technical support,technical support,– specialized softwarespecialized software
They can charge as much as they choose for their They can charge as much as they choose for their Linux distributionsLinux distributions
88
Linux DistributionsLinux Distributions
99
UNIX ConceptsUNIX Concepts
ShellShell– The interface between user and OSThe interface between user and OS
Hierarchical StructureHierarchical Structure– Directory and subdirectory organizationDirectory and subdirectory organization
Layered componentsLayered components– Layers of software cover hardwareLayers of software cover hardware
1010
1111
Choosing Your ShellChoosing Your Shell
Shells interpret commands and act as first-class Shells interpret commands and act as first-class programming languageprogramming language
A default shell is associated with your account A default shell is associated with your account when createdwhen created
A list of some UNIX shells:A list of some UNIX shells:– BourneBourne– C shellC shell– KornKorn– Bash, tcshBash, tcsh
1212
Choosing User Names Choosing User Names and Passwordsand Passwords
To use UNIX, a user must log in by providing a To use UNIX, a user must log in by providing a unique user name and passwordunique user name and password
UNIX system administrators create accounts by UNIX system administrators create accounts by adding user names and passwordsadding user names and passwords
1313
Connecting to a UNIX SystemConnecting to a UNIX System
Directly via attached terminalDirectly via attached terminal
Via terminal window in windowing systemVia terminal window in windowing system
Remotely through telnet, rsh or sshRemotely through telnet, rsh or ssh
1414
Connecting to UNIXConnecting to UNIXUsing TelnetUsing Telnet
telnet is terminal emulation softwaretelnet is terminal emulation software– Deemed insecureDeemed insecure– Better: sshBetter: ssh
connects to Unix serverconnects to Unix server– Once connected to a UNIX host, work with Once connected to a UNIX host, work with
UNIX may beginUNIX may begin– Uses IP addresses or domain names to Uses IP addresses or domain names to
access remote systemsaccess remote systems
1515
Entering CommandsEntering Commands
To interact with UNIX, a command is entered To interact with UNIX, a command is entered at the command promptat the command prompt
UNIX is case-sensitive and most commands UNIX is case-sensitive and most commands are typed in lower caseare typed in lower case
Two categories of commandsTwo categories of commands– User-level: perform tasksUser-level: perform tasks– System administration: system managementSystem administration: system management
1616
Entering CommandsEntering Commands
The date commandThe date command– Displays the system date, which the system Displays the system date, which the system
administrator maintainsadministrator maintains
The cal commandThe cal command– Shows the system calendarShows the system calendar
The who commandThe who command– Shows who is using the system and their Shows who is using the system and their
current locationcurrent location
1717
Entering CommandsEntering Commands
1818
Entering CommandsEntering Commands
1919
Entering CommandsEntering Commands
2020
Entering CommandsEntering Commands
Command-line editing (shell dependent)Command-line editing (shell dependent)– Certain keystrokes perform command-line Certain keystrokes perform command-line
editingediting– Use up and down arrow keys to scroll Use up and down arrow keys to scroll
through command historythrough command history
Multiple command entryMultiple command entry– Separate commands with semicolon(;)Separate commands with semicolon(;)The clear commandThe clear command– Clears the current screenClears the current screen
2121
Getting HelpGetting Help
The man program displays the UNIX online reference The man program displays the UNIX online reference manual, called the man pages, for help purposesmanual, called the man pages, for help purposes
2222
Viewing FilesViewing Files
Use cat, more, and less to view an entire Use cat, more, and less to view an entire file contentsfile contents– cat displays a whole file at one timecat displays a whole file at one time– more displays a file one screen at a time, more displays a file one screen at a time,
allowing scroll down allowing scroll down
– less displays a file one screen at a time, less displays a file one screen at a time, allowing scroll down and upallowing scroll down and up
2323
Viewing FilesViewing Files
Use head and tail to view the first few or Use head and tail to view the first few or last few lines of a filelast few lines of a file– head displays the first few lineshead displays the first few lines– tail displays the last few linestail displays the last few lines
2424
Logging Out of UNIXLogging Out of UNIX
Logging out ends your current process Logging out ends your current process and indicates to UNIX that you are and indicates to UNIX that you are finishedfinished
Logging out is shell dependentLogging out is shell dependent– Bourne, Korn, Bash – exit commandBourne, Korn, Bash – exit command– C shell – logout commandC shell – logout command
2525
Changing PasswordsChanging Passwords
For security purposes, changing For security purposes, changing passwords is necessarypasswords is necessary– Use the passwd commandUse the passwd command– UNIX allows new password if:UNIX allows new password if:
The new password differs by at least three The new password differs by at least three characterscharactersIt has six or more characters, including at least It has six or more characters, including at least two letters and one numbertwo letters and one numberIt is different from the user nameIt is different from the user name
2626
Understanding the Role of the Understanding the Role of the UNIX System AdministratorUNIX System Administrator
User “root” manages the UNIX systemUser “root” manages the UNIX system– Adds users and deletes old accountsAdds users and deletes old accounts– Also called the superuserAlso called the superuser– Unlimited permission to alter systemUnlimited permission to alter system
Unix file systemUnix file system
2828
Understanding the UNIXUnderstanding the UNIXFile SystemFile System
A file is the basic component for data storageA file is the basic component for data storage– UNIX considers everything it interacts with a fileUNIX considers everything it interacts with a file
A file system is UNIX’s way of organizing files on A file system is UNIX’s way of organizing files on mass storage (disk) devicesmass storage (disk) devices– A physical file system is a section of the hard disk that A physical file system is a section of the hard disk that
has been formatted to hold fileshas been formatted to hold files
The file system is organized in a hierarchical The file system is organized in a hierarchical structure similar to an inverted treestructure similar to an inverted tree
2929
3030
Understanding the Standard Understanding the Standard Tree StructureTree Structure
The structure starts at the root levelThe structure starts at the root level– Root is the name of the file at this basic level and it is Root is the name of the file at this basic level and it is
denoted by the slash character (/)denoted by the slash character (/)
A directory is a file that can contain other files A directory is a file that can contain other files and directoriesand directories
A subdirectory is a directory within a directoryA subdirectory is a directory within a directory– The subdirectory is considered the child of the parent The subdirectory is considered the child of the parent
directorydirectory
3131
Exploring the Root File System Exploring the Root File System
UNIX must mount a file system before any UNIX must mount a file system before any programs can access files on itprograms can access files on it
To mount a file system is to connect it to To mount a file system is to connect it to the directory tree structurethe directory tree structure
The root file system is mounted by the The root file system is mounted by the kernel when the system startskernel when the system starts
3232
Exploring the Root File Exploring the Root File System System
The root directory contains sub-directories The root directory contains sub-directories that contain files:that contain files:– /bin/bin contains binaries, or executables needed contains binaries, or executables needed
to start the system and perform system tasksto start the system and perform system tasks– /boot/boot contains files needed by the bootstrap contains files needed by the bootstrap
loader as well as kernel imagesloader as well as kernel images– /dev/dev contains system device reference files contains system device reference files
3333
3434
Exploring the Root File Exploring the Root File System System
Root subdirectories continued:Root subdirectories continued:– /etc/etc contains configuration files that the contains configuration files that the
system uses when the computer startssystem uses when the computer starts– /lib/lib contains kernel modules, security contains kernel modules, security
information, and the shared library imagesinformation, and the shared library images– /mnt/mnt contains mount points for temporary contains mount points for temporary
mounts by the system administratormounts by the system administrator– /proc/proc is a virtual file system allocated in is a virtual file system allocated in
memory onlymemory only
3535
Exploring the Root File Exploring the Root File System System
Root subdirectories continued:Root subdirectories continued:– /root/root is the home directory of the root user, or is the home directory of the root user, or
the system administratorthe system administrator– /sbin/sbin contains essential network programs contains essential network programs
used only by the system administrator used only by the system administrator – /tmp/tmp is a temporary place to store data during is a temporary place to store data during
processing cyclesprocessing cycles– /var/var contains subdirectories which have sizes contains subdirectories which have sizes
that often change, such as error logsthat often change, such as error logs
3636
Understanding PathsUnderstanding Pathsand Pathnamesand Pathnames
To specify a file or directory, use its To specify a file or directory, use its pathname, which follows the branches of pathname, which follows the branches of the file system to the desired filethe file system to the desired file– A forward slash (/) separates each directory A forward slash (/) separates each directory
namename– The UNIX command prompt may indicate The UNIX command prompt may indicate
your location within the file systemyour location within the file system– Use the UNIX pwd command to display the Use the UNIX pwd command to display the
current path namecurrent path name
3737
Navigating the File System Navigating the File System
To navigate the UNIX directory structure, To navigate the UNIX directory structure, use the cd (change directory) commanduse the cd (change directory) command
UNIX refers to a path as either:UNIX refers to a path as either:– Absolute - begins at the root level and lists all Absolute - begins at the root level and lists all
subdirectories to the destination filesubdirectories to the destination file– Relative - begins at your current working Relative - begins at your current working
directory and proceeds from there directory and proceeds from there
3838
Listing Directory ContentsListing Directory Contents
The ls (list) command displays a directory’s contents, The ls (list) command displays a directory’s contents,
including files and subdirectoriesincluding files and subdirectories
3939
Listing Directory ContentsListing Directory Contents
ls options:ls options:– aa include files with “.”include files with “.”– ll long formatlong format– RR recursively list subdirectoriesrecursively list subdirectories
4040
Listing Directory ContentsListing Directory Contents
4141
Managing Directories and Managing Directories and FilesFiles
mkdir (make directory) commandmkdir (make directory) command– Create a new directoryCreate a new directory
rmdir (make directory) commandrmdir (make directory) command– Delete an empty directoryDelete an empty directory
cp (copy) commandcp (copy) command– Copy files from one director to anotherCopy files from one director to another
rm (remove) commandrm (remove) command– Delete filesDelete files
4242
Setting File PermissionsSetting File Permissions
4343
Setting File PermissionsSetting File Permissions
File PermissionsFile Permissions
rr Owner has readOwner has read
ww Owner has writeOwner has write
xx Owner has executeOwner has execute
rr Group has readGroup has read
-- Group does not have writeGroup does not have write
xx Group has executeGroup has execute
rr Others have readOthers have read
-- Others do not have writeOthers do not have write
xx Others have executeOthers have execute
4444
Setting File PermissionsSetting File Permissionsfor Securityfor Security
chmod commandchmod command– To set file permissionsTo set file permissions– Settings are read (r), write (w), execute (x)Settings are read (r), write (w), execute (x)– The three types of users are owners, groups, The three types of users are owners, groups,
and othersand others
Setting permissions to directoriesSetting permissions to directories– Use the execute (x) to grant accessUse the execute (x) to grant access
4545
Using Input and Error Using Input and Error RedirectionRedirection
You can use redirection operators to retrieve You can use redirection operators to retrieve input from something other than the standard input from something other than the standard input device and send output to something other input device and send output to something other than the standard output device than the standard output device
Examples of redirection:Examples of redirection:– Redirect the ls command output to a file, instead of to Redirect the ls command output to a file, instead of to
the monitor (or screen)the monitor (or screen)– Redirect a program that receives input from the Redirect a program that receives input from the
keyboard to receive input from a file insteadkeyboard to receive input from a file instead– Redirect error messages to files, instead of to the Redirect error messages to files, instead of to the
screen by defaultscreen by default
4646
Redirecting OutputRedirecting Output
The greater than sign (>) is called a The greater than sign (>) is called a redirection symbolredirection symbol
Create a new file or overwrite an existing Create a new file or overwrite an existing file by attaching (>) to a command that file by attaching (>) to a command that produces outputproduces output
To append to an existing file, use two To append to an existing file, use two redirection symbols (>>)redirection symbols (>>)
4747
Creating new filesCreating new files
using cat output redirectionusing cat output redirectionconcatenate text via output redirectionconcatenate text via output redirection
touch command on new filetouch command on new fileinvoke editor for new fileinvoke editor for new file
4848
Manipulating FilesManipulating Files
Delete files when you no longer neededDelete files when you no longer needed– rm command rm command
permanently removes a file or an empty directorypermanently removes a file or an empty directory
-r option removes a directory and everything it contains -r option removes a directory and everything it contains
Copy files as a means of back-up or as a means Copy files as a means of back-up or as a means to assist with new file creationto assist with new file creation– cp commandcp command
copies the file(s) specified by the source path to the location copies the file(s) specified by the source path to the location specified by the destination path specified by the destination path
4949
Manipulating FilesManipulating Files
Moving a fileMoving a file– mv commandmv command
removes file from one directory and places it in removes file from one directory and places it in anotheranother
Finding a file helps you locate it in the Finding a file helps you locate it in the directory structuredirectory structure– find commandfind command
searches for the file that has the name you specifysearches for the file that has the name you specify
5050
Manipulating FilesManipulating Files
Combining files using output redirectionCombining files using output redirection– cat commandcat command
concatenate text of two different files via output redirectionconcatenate text of two different files via output redirection
– paste commandpaste commandjoins text of different files in side by side fashionjoins text of different files in side by side fashion
Extracting fields of a file using output redirectionExtracting fields of a file using output redirection– cut commandcut command
removes specific columns or fields from a fileremoves specific columns or fields from a file
5151
Sorting FilesSorting Files
sortsort command command– sort options:sort options:
alphabetical or numerical sortalphabetical or numerical sort
specify sort key(s)specify sort key(s)
5252
Commands as filtersCommands as filters
pipe operator (|) pipe operator (|)
redirects the output of one commandredirects the output of one command
to the input of another command to the input of another command – Example: redirect output of “ls” to “more”Example: redirect output of “ls” to “more”
pipe operator can connect several pipe operator can connect several commands on the same command linecommands on the same command line
5353
Using PipesUsing Pipes
Using pipe operators and connecting commands is useful when viewing directory information
5454
Using the grep CommandUsing the grep Command
searches for a specific pattern in a file, such as searches for a specific pattern in a file, such as a word or phrasea word or phrase
grep’s options and wildcard support allow for grep’s options and wildcard support allow for powerful search operationspowerful search operations
You can increase grep’s usefulness by You can increase grep’s usefulness by combining with other commands, such as head combining with other commands, such as head or tailor tail
5555
Using the grep CommandUsing the grep Command
grep can be part of pipe
5656
Regular expressionsRegular expressions
Character matchingCharacter matching– Each character matches itselfEach character matches itself– . Matches any character. Matches any character– ^ line-begin, $ line-end^ line-begin, $ line-end– [abc] [a-z] [0-9a-zA-Z][abc] [a-z] [0-9a-zA-Z]
matches one of the charactersmatches one of the characters
– [:digit:] [:lower:] [:upper:] [:alnum][:digit:] [:lower:] [:upper:] [:alnum]– [^abc][^abc]
Matches everything elseMatches everything else
Repetition: *Repetition: *
5757
Extended regular expressionsExtended regular expressions
Repetitions:Repetitions:– * zero or more* zero or more– + one or more+ one or more– ? zero or one? zero or one– {n} exactly n times{n} exactly n times– {n,m} at least n, at most m{n,m} at least n, at most m– {n,} at least n times{n,} at least n times
Grouping:Grouping:– ( )( )– | | logical or logical or
5858
grep versionsgrep versions
grepgrep– Supports basic regular expressionsSupports basic regular expressions
egrepegrep– supports extended regular expressionssupports extended regular expressions
fgrepfgrep– searches for fixed stringssearches for fixed strings
5959
Using the diff CommandUsing the diff Command
determines the minimal changes needed determines the minimal changes needed to convert file1 to file2to convert file1 to file2
output displays the line(s) that differoutput displays the line(s) that differ
output contains codes to indicate which output contains codes to indicate which lines must be added, changed or deletedlines must be added, changed or deleted
applied via applied via patchpatch command command
6060
Using the Manipulate and Using the Manipulate and Format CommandsFormat Commands
These commands are: sed, trThese commands are: sed, tr
Used to edit and transform the Used to edit and transform the appearance of data before it is appearance of data before it is displayed or printeddisplayed or printed
Example of trExample of tr– cat file | tr ‘:’ ‘/’ > newfilecat file | tr ‘:’ ‘/’ > newfile
6161
Stream editor: sedStream editor: sed
sed is a UNIX editor that allows you to make sed is a UNIX editor that allows you to make global changes to large filesglobal changes to large files
Minimum requirements are an input file and a Minimum requirements are an input file and a command that lets sed know what actions to command that lets sed know what actions to apply to the fileapply to the file
sed commands have two general formssed commands have two general forms– Specify an editing command on the command lineSpecify an editing command on the command line– Specify a script file containing sed commandsSpecify a script file containing sed commands
6262
sed command examplessed command examples
command language similar to vicommand language similar to vi
syntax: syntax: – address-range commandaddress-range command
examples:examples:– 1,$ s/one/two/1,$ s/one/two/
– 5 p5 p
– 1,29 d1,29 d
6363
vi editorvi editor
6464
Using the vi EditorUsing the vi Editor
Called vi because it is visual – it immediately Called vi because it is visual – it immediately displays on screen the changes that you make displays on screen the changes that you make to textto text
It is also modal – works in three modesIt is also modal – works in three modes– Insert mode - lets you enter textInsert mode - lets you enter text– Command mode - lets you enter commands to Command mode - lets you enter commands to
perform editing tasksperform editing tasks– Extended (ex) command set mode - lets you use an Extended (ex) command set mode - lets you use an
extended set of editing commands extended set of editing commands
6565
Using the vi EditorUsing the vi Editor
To create a new file in the vi editor, type vi and the name of the new file at the command prompt
6666
Using the vi EditorUsing the vi Editor
When started, the vi editor is in command When started, the vi editor is in command modemode– In order to insert text, you must issue the “i” In order to insert text, you must issue the “i”
command to enter insert modecommand to enter insert mode– You can repeat the line just entered with the You can repeat the line just entered with the
repeat command (.)repeat command (.)– To edit what you’ve just typed, move the To edit what you’ve just typed, move the
cursor with the various keyboard cursor cursor with the various keyboard cursor movement keysmovement keys
6767
Using the vi EditorUsing the vi Editor
In insert mode, every character you type appears on the screen
6868
Using the vi EditorUsing the vi Editor
The repeat command repeats the last insertion, or line. Now, edit the new line in order to create the next item
6969
Using the vi EditorUsing the vi Editor
7070
Using the vi EditorUsing the vi Editor
While still in command mode:While still in command mode:– To delete text, move to a character and then To delete text, move to a character and then
type “x”type “x”– You can undo a command (reverse its effects) You can undo a command (reverse its effects)
by typing “u”by typing “u”– To search for a text pattern, type a forward To search for a text pattern, type a forward
slash (/), type the pattern, and press Enterslash (/), type the pattern, and press Enter
7171
Using the vi EditorUsing the vi Editor
7272
Using the vi EditorUsing the vi Editor
7373
Using the vi EditorUsing the vi Editor
The status line at the bottom of the screen displays information, including line-oriented commands and error messages
7474
Using the vi EditorUsing the vi Editor
During text searches, you can replace, too. Use line-oriented commands in ex mode to perform this action
7575
Using the vi EditorUsing the vi Editor
Saving a File and Exiting viSaving a File and Exiting vi– You should always save the file before exiting You should always save the file before exiting
vi, otherwise changes are lostvi, otherwise changes are lost– To save a file and continue working on it, type To save a file and continue working on it, type
the :w (write) commandthe :w (write) command– While in command mode, use the :wq (write While in command mode, use the :wq (write
and quit) command to save and exit, or the ZZ and quit) command to save and exit, or the ZZ command to exit after saving command to exit after saving
7676
Using the vi EditorUsing the vi Editor
In vi, you can also:In vi, you can also:– Add text from another fileAdd text from another file– Leave vi temporarily to perform other UNIX Leave vi temporarily to perform other UNIX
tasks, then return to your filetasks, then return to your file– Change your display while editing, such as Change your display while editing, such as
adding line numbering to help editingadding line numbering to help editing– Copy, cut, and paste text to help editingCopy, cut, and paste text to help editing– Print text filesPrint text files– Cancel an editing sessionCancel an editing session
7777
Using the vi EditorUsing the vi Editor
7878
UNIX UtilitiesUNIX Utilities
UNIX utilities let you create and manage files, UNIX utilities let you create and manage files, run programs, produce reports, and generally run programs, produce reports, and generally interact with the systeminteract with the system
They also offer a full range of services that let They also offer a full range of services that let you monitor and maintain the system and you monitor and maintain the system and recover from a wide range of errorsrecover from a wide range of errors
Utility programs are vital for working through an Utility programs are vital for working through an OS and new utilities are continually being added OS and new utilities are continually being added in order to make UNIX run more efficientlyin order to make UNIX run more efficiently
7979
UNIX UtilitiesUNIX Utilities
UNIX utilities are classified into seven major UNIX utilities are classified into seven major function areas dictated by user needs function areas dictated by user needs – File processingFile processing– System statusSystem status– NetworkingNetworking– CommunicationsCommunications– ProgrammingProgramming– Source code managementSource code management– MiscellaneousMiscellaneous
8080
8181
8282
8383
8484
8585
8686
8787
8888
8989
C Programming in aC Programming in a
UNIX EnvironmentUNIX Environment
9090
9191
Creating a C ProgramCreating a C Program#include <stdio.h>
main() { printf("hello world\n");}
Stored as:Stored as: one.cone.c
Compiled and linked as:Compiled and linked as: gcc one.cgcc one.c
run as:run as: ./a.out./a.out
9292
Compilation ProcessCompilation Process.c and .h
.o
a.out
.i
.s
gcc -E
gcc -S
gcc -c
.a ar
gcc -o
9393
A simple C programA simple C program
#include <stdio.h>#include <stdio.h>main(int argc, char* argv[]) {main(int argc, char* argv[]) { if (argc > 1)if (argc > 1) printf("hello %s\n", argv[1]);printf("hello %s\n", argv[1]); elseelse printf("hello world\n");printf("hello world\n");}}
command line argumentscommand line arguments
9494
A simple C programA simple C program
to compile:to compile:
gcc two.cgcc two.c
produces:produces: a.out a.out
oror
gcc -c two.cgcc -c two.c
produces:produces: two.o two.o
9595
A simple C functionA simple C function
#include <math.h>#include <math.h>
int compute(int x, int y) {int compute(int x, int y) { double tx = x, ty = y, tr;double tx = x, ty = y, tr; tr = pow(tx, ty);tr = pow(tx, ty); return (int) tr;return (int) tr;}}
uses math libraryuses math library
9696
Multiple source filesMultiple source files
9797
A main programA main program#include <stdio.h>#include <stdio.h>main() {main() { int x, y, p;int x, y, p; printf("This program computes x^y\n");printf("This program computes x^y\n"); printf("Enter x: ");printf("Enter x: "); scanf("%d", &x);scanf("%d", &x); printf("Enter y: ");printf("Enter y: "); scanf("%d", &y);scanf("%d", &y); p = compute(x, y);p = compute(x, y); printf("Result: %d\n", p);printf("Result: %d\n", p);}}
asks for user inputasks for user input
9898
Steps to create an executableSteps to create an executable
to compile:to compile:
gcc –c compute.cgcc –c compute.c
gcc –c power.cgcc –c power.c
gcc compute.o power.o –lm –o powergcc compute.o power.o –lm –o power
to runto run
./power./power
9999
make utilitymake utility
has configuration file that specifies has configuration file that specifies dependencies: dependencies: makefilemakefile
checks timestamps on fileschecks timestamps on files
recompiles necessary filesrecompiles necessary files
100100
makefilemakefile
power: power.o compute.opower: power.o compute.o
gcc power.o compute.o -o power -lmgcc power.o compute.o -o power -lm
power.o: power.cpower.o: power.c
gcc -c power.cgcc -c power.c
compute.o: compute.ccompute.o: compute.c
gcc -c compute.cgcc -c compute.c
101101
C++ Programming in aC++ Programming in a
UNIX EnvironmentUNIX Environment
102102
Creating a C++ ProgramCreating a C++ Program#include <iostream>
main() { cout << "hello world" << endl;}
Stored as:Stored as: one.ccone.cc
Compiled and linked as:Compiled and linked as: g++ one.ccg++ one.cc
run as:run as: ./a.out./a.out
103103
A simple C++ programA simple C++ program
#include <iostream>#include <iostream>
main(int argc, char* argv[]) {main(int argc, char* argv[]) { if (argc > 1)if (argc > 1) cout << "hello " << argv[1] << endl;cout << "hello " << argv[1] << endl; elseelse cout << "hello world\n";cout << "hello world\n";}}
command line argumentscommand line arguments
104104
A simple C++ programA simple C++ program
to compile:to compile:
g++ two.ccg++ two.cc
produces:produces: a.out a.out
oror
g++ -c two.ccg++ -c two.cc
produces:produces: two.o two.o
105105
C++ classesC++ classes
Class header and bodyClass header and body
Header in header fileHeader in header file .h.h
Body in body fileBody in body file .cc or .C.cc or .C– includes header fileincludes header file
main function still requiredmain function still required
106106
A simple C++ class headerA simple C++ class header
#ifndef COUNTER_H#ifndef COUNTER_H#define COUNTER_H#define COUNTER_Hclass Counter {class Counter { int value;int value; public:public: Counter();Counter(); void increment(int);void increment(int); void reset();void reset(); int getValue();int getValue();};};#endif#endif
107107
A simple C++ class bodyA simple C++ class body
#include "Counter.h"#include "Counter.h"
Counter::Counter() {Counter::Counter() { reset();reset();}}void Counter::increment(int n=1) {void Counter::increment(int n=1) { value += n;value += n;}}void Counter::reset() {void Counter::reset() { value = 0;value = 0;}}int Counter::getValue() {int Counter::getValue() { return value;return value;}}
108108
main C++ programmain C++ program
#include <iostream>#include <iostream>#include "Counter.h"#include "Counter.h"main() {main() { Counter c;Counter c; int value;int value; cout << "enter value: ";cout << "enter value: "; cin >> value;cin >> value; c.increment(value);c.increment(value); cout << "counter now: " cout << "counter now: " << c.getValue() << endl;<< c.getValue() << endl;}}
109109
makefilemakefile
count: Counter.o main.ocount: Counter.o main.o
g++ Counter.o main.o -o countg++ Counter.o main.o -o count
Counter.o: Counter.CCounter.o: Counter.C
g++ -c Counter.Cg++ -c Counter.C
main.o: main.Cmain.o: main.C
g++ -c main.Cg++ -c main.C