Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Introduction to Programming in C / C++ / ROOT Christopher Crawford 2008-10-01 Computer Architecture ALU Cache Registers • CPU - (32/64 bit words) Instructions • • - Read / Write / Arithmetic Branching / Subroutines Registers • • Program counter Stack counter (subroutines) - • Pre-emptive multitasking Memory – bytes (8 bit bytes) - Address space (address, data): • • • data (variables) text (CPU instructions) I/O (not memory at all) - • Virtual memory (paging) Input / Output (N-bit buses) - busses • • • • - PCI- expansion slots, Ethernet IDE, SATA - hard drive (HD) USB – keyboard, mouse LPC - serial, parallel, floppy IRQ – interrupt requests DMA – direct memory access Operating System BIOS – first instructions executed, loads and runs OS kernel Process control - • Paging (swap space) Segmentation violations! • • - File system All external data mounted into common directory tree Devices are treated as files • • Device drivers, accesses I/O programs which further interact with kernel (process, mem, i/o) Eg.: ls, cd, cp, mv, ps, mount, etc Compiler • Compiler chain - • /dev/ttyS1 /dev/stdin, /dev/stdout ) Modules User interface to the kernel Interpreted ‘language’ Shell scripts Eg.: bash, tcsh, tcl, perl Utilities I/O devices - • Memory management - • Scheduler (multitasking) Environment for processes Threads (separate execution lines in a single program Shell • • • • Kernel – controls CPU • (#include) (.c .s) (.s .o) (.o .so, a.out) (.so, a.out memory) Build tool chain - • Preprocessor Compiler Assembler Linker Loader Configure Make Debugging Libraries: - Std C library (autoconf) (automake) (gdb, gprof) *.so *.a *.h (glibc) File System All I/O is organized into one tree • • Path: parent/child/grandchild/… Mounts: (instead of a: b: c: drives) - • • Drivers, raw I/O: /dev Kernel I/O: /proc, /sys Special directories • • • • Single disk at base of file system Other disks ‘mounted’ (grafted) onto branches of file system Root (base) Current (cwd) Parent Home ($HOME) / . .. ~ Directory structure • • Std names for common directories bin, etc, lib, include, share, src Repeating hierarchy of structure /, /usr, /usr/local, /usr/X11, /opt, ... / etc bin (binaries) sbin lib var .. tmp - root directory - configuration - executable - secure code - libraries - databases, spools, - temporary files boot/ - kernel image mnt/ usb,floppy - mounted directories dev/ - I/O devices zero,null,ttyS0,parport0 std{in,out,err} -> /proc/self/fd/{0,1,2} sca,sca0,sca1, scb,scb0, .., cdrom -> scd0 proc/ - CPU processes cpuinfo,meminfo, - diagnostics 16117/cwd,environ,cmdline fd/{0,1,2} -> /dev/pts/{0,1,2} sys/ - system info usr/bin,lib,share… software local/bin,lib,… X11/bin,lib,… opt/ - distribution - custom software - GUI software - commercial software root/ - superuser directory home/ - user directories chris2/ etc,bin,lib data/ - shared data bash – Bourne-again shell Program execution ENVIRONMENT variables 1. grep Input / Output redirection 2. find Utilities 3. sed Memory structure Address Space Size in bytes (not words) • type symbol address data (C/C++) (assembly) (hardware) (hardware) Text (code) Data (globals) Stack (auto,temp) Heap (dynamic) Type modifiers: • • • auto, static, extern const, volatile [un]signed Discrete • • • • • 4 GB (32 bit pointers) bool char short integer long long 2 256 65536 4.295G 18.447E 1 bit 8 bits 16 bits 32 bits 64 bits 1 byte 2 bytes 4 bytes 8 bytes 1 word 2 words 7e-7 2e-16 32 bits 64 bits 4 bytes 8 bytes 1 word 2 words Continuous • • Program parts: • • • • Memory chart: • • • • Data Types float double Compound • • • • • void pointers references arrays structures none (no type) 32/64 CPU dependent 0 alias only N * base type Σ base types Sample C program #include <stdio.h> #include <string.h> /* library function prototypes */ int n = 1; float x = 2.3; /* variable declarations */ int add( float x, float y ); /* function prototype */ int main( int argc, char** argv ) { int y = add( n, x ); y = y + 1; printf("y = %d\n", y); /* main program */ char name[80]; printf( "who are you?\n" ); fgets( name, 80, stdin ); if (!strcmp( name, "joe\n" )) { int i; for ( i=0; i<5; ++i ) { printf( "go away!\n" ); } } else { printf( "hello, %s", name ); } return 0; /* automatic variable declaration */ /* statement with assignment operator */ /* formatted print statement */ /* character string (array) declaration */ /* conditional branching */ /* loop */ /* return value of function */ } int add( float x, float y ) { return x + y; } /* subroutine function */ Structure of a C program Essentially a collection of declarations and definitions of variables and functions A. Expressions Execution starts at B. Blocks – group of statements • Types are defined in the same way they are used • Strongly typed Compiler only scans file once int fn ( float var, …) Function definitions are lists of variable declarations and statements executed linearly Statements consist of a) Expressions, b) Blocks, c) Flow Control variables and constants tied together with operators (functions) { statement; statement; ... } int main ( int argc, char** argv) { Everything must be defined before it is used • • • C. Flow control Statements • Conditionals if (cond) statement else statement switch (key) { case label: statement; break; default: statement; } • Loops while (cond) statement do statement while (cond); for (init; cond; incr) statement break; continue; (inside loops) goto label; label: statement • Exceptions try statement catch (err) statement throw err; C/C++ punctuation /* */ // C-style comments C++-style comments {} [] () <> statement block, array initializer data array index, declaration function arguments, expression ordering, initializer templates, #include <stdlib.h> "string" 'c' character string single character , ; : # separates function arguments end of statements and declarations statement label preprocessor directives A-Za-z_0-9 valid characters in a name, first letter cannot be 0-9 C/C++ Operators – precedence & associativity :: (unary <-, binary ->) () [] -> . -> ++ -- + - ! ~ (unary) <(type) * & sizeof .* ->* -> * / % -> + -> << >> -> < <= > >= -> == != -> & -> ^ -> | -> && -> || -> ?: <= += -= *= /= %= <&= ^= |= <<= >>= , -> scope arguments, element, index, member inc/decrement, pos., neg., not, complement typecast, dereference, address, size function pointer multiply, divide, modulo add, subtract bit shift left/right; (stream insert/extract) comparison test equality bitwise and " xor " or logical and " or if-then-else assignment sequence IEEE Floating Point Numbers Integers Standard C library – glibc <complex.h> <math.h> <signal.h> <stdarg.h> <stdio.h> <stdlib.h> <string.h> <time.h> – complex number arithmetic and functions – trigonometric and exponential functions – signal handling – functions with indefinite # of arguments – standard input / output – memory allocation, process control, conversions, random numbers – string comparison, memory copying – time and date manipulation and formatting <assert.h> <ctype.h> <errno.h> <fenv.h> <float.h> <inttypes.h> <iso646.h> <limits.h> <locale.h> <setjmp.h> <stdbool.h> <stddef.h> <stdint.h> <tgmath.h> <wchar.h> <wctype.h> – debugging, report assertions which are not true – character types – error conditions – floating point environment – floating point parameters – macros for printf – words for logical operators – limits of each number type – international messages – longjump – boolean type – NULL pointer – portable integer types – float math functions – 2-byte characters (unicode) – 2-byte characters (unicode) Argument passing between functions Arguments are passed on the execution stack • First temporary variables of the function Three different argument-passing styles, based on compound types: • A) pass by value - • • int fn ( int & a ) fn ( x ) New symbol ‘a’ labeling old variable, old value is rewritten Arguments can be used to return multiple values from function Only variable names can be used as function arguments (not just a value) This is the FORTRAN method of passing arguments C) pass by pointer - fn ( x ) Value of a copied, used to create new variable ‘a’ on the stack Original variable ‘x’ remains untouched B) pass by reference - int fn ( int a ) int fn ( int * a ) fn ( &x ) New pointer variable ‘a’ created on the stack, points to old value of ‘x’ Clunky way of implementing (B) Arrays are always passed by address only: • • • • Array type (pointer) Double array (pointer) int fn ( int v[3] ) int fn ( int * v ) int fn ( int w[][3] ) int fn ( int (*w)[3] ) fn ( v ) fn ( v ) fn ( w ) fn ( w )