A C++ Crash Course Part II

download A C++ Crash Course Part II

of 81

  • date post

  • Category


  • view

  • download


Embed Size (px)


A C++ Crash Course Part II. UW Association for Computing Machinery http://www.cs.washington.edu/orgs/acm/tutorials acm@cs.washington.edu. Questions & Feedback to Albert J. Wong (awong). C Preprocessor #include, #define, #if, etc. __FILE__, __LINE__ Multiple File Development Header Files - PowerPoint PPT Presentation

Transcript of A C++ Crash Course Part II

  • A C++ Crash CoursePart IIUW Association for Computing Machinery http://www.cs.washington.edu/orgs/acm/tutorialsacm@cs.washington.eduQuestions & Feedback to Albert J. Wong (awong)

  • What We Will CoverC Preprocessor#include, #define, #if, etc.__FILE__, __LINE__

    Multiple File DevelopmentHeader FilesSeparate Compilation

    Compilation ProcessCompilationLinking

    Advanced Modifiersconst, static, extern, volatile


    Operator Overloading

    ClassesConstructors, DestructorsInheritanceVirtual (dynamic dispatch)

    Dynamic Memorynew, delete, delete[]malloc, calloc, realloc, free

    C/C++ I/O Functions

  • What We Are NOT CoveringAnything in the first tutorialPointers, arrays, referencesstructs, unions, enums

    Weird InheritanceMultiple inheritanceVirtual inheritance (NOT dynamic dispatch)

    TemplatesGeneric ProgrammingExceptionsSTLMakefiles

  • Basics refresher QuizWrite a struct called Point3D that represents a 3D point. Give it 3 member variables, x, y, z with type double.Given that struct definition, and following code:Count how many times a Point3D is createdList all places memory is allocated, and the type of memory allocated

    typedef struct Point3D Point3D;Point3D add(Point3D *a, Point3D *b) {Point3D p;p.x = a->x + b->x;p.y = a->y + b->y;return p}int main(void) {Point3D p1 = {0,1};Point3D p2 = {3,4};Point3D p3 = add(&p1, &p2);return 0;}

  • Declarations - (bad) Example

    int main(void) {int result;...

    result = add(20, 3);

    ...return 0;}

    int add(int a, int b) {return a + b;}

    What is wrong with the following code? Will it compile in C? in C++?Hint: It has to do with the declaration and use of add.

  • Declaration Regions

    int main(void) {int result;int add(int,int);...

    result = add(20, 3);

    ...return 0;}

    int add(int a, int b) {return a + b;}...int add(int,int);

    int main(void) {int result;...

    result = add(20, 3);

    ...return 0;}

    int add(int a, int b) {return a + b;}...

    Corrected Code 1 (local prototype)Corrected Code 2 (global prototype)

  • Declarations - SummaryDeclarations can be separate from definitionsFunction declarations are called prototypesDeclarations should be given before usage

    C & C++ handle undeclared functions differentlyIn C++ this is an errorIn C, the function is implicitly declared with the type:int name(...);

    Declarations and definitions are separate concepts

  • I/O C-styleBasic functions:printf, scanf, fprintf, fscanf, sprintf, sscanf, etc.gets, puts, getc, putc, getcharread, write, fread, fwriteC-style IO is an acquired taste. Learn to like it.We will cover the basics of the formated family of functions (printf, scanf, etc). For the others, read the man pages in Unix.

  • printfIn C, all devices are treated like filesThree standard files are:stdinOften the keyboardstdoutOften the text consolestderrOften the text consoleprintf(....) is fprintf(stdout, ....)The format string is a pattern for the output; it describes how to display the arguments to printf.Snprintf write to the string buf. The variable n specifies the size of the buffer.printf returns the number of characters writtenprintf(char *format_string, ...);fprintf(FILE*, char *format_string, ...);snprintf(char* buf, size_t n, char *format_string, ...);

  • format stringFormat strings are normal strings with embedded conversion specifications which are placeholders for argumentsConversion specifications are a % and a letter with an optional set of arguments in between the % and letter.To print a %, you need to write %%

    Example:printf(Here is a number: %d\n, 10);

    %d is the conversion specification for signed integers.

  • Conversion SpecificationsConversion Specifications:%d, %i -- signed integer%u -- unsigned integer%f -- floating point number%c -- character%s -- string%x -- hexadecimal value%p -- pointerConverion specifications tell how to translate a data value into a stringOptions:l -- long (32-bit value)ll -- long long (64-bit value)n -- field width of n digits.n -- precision of n digits0 -- fill unused field with 0sThere are many more! Read man pages, or Google it.

  • printf quiz!printf(%.3f rounded to 2 decimals is %.2f\n, 2.325, 2.325);

    printf(%d in hex is: %04x\n, 24, 24);

    printf(Quizzes are fun, ja?\n);Figure out the output of the following:

  • scanfscanf(....) is fscanf(stdin, ....)All arguments ot scanf must be pointers (or arrays)scanf does almost no size checks. It is easy to get a buffer overflow here. Make sure you use a field length specifier with the %s conversion specifer!!!scanf returns the number of items read.scanf(char *format_string, ...);fscanf(FILE*, char *format_string, ...);sscanf(char*, char *format_string, ...);

  • scanf Examplesint items_read;

    Read a number:int num;items_read = scanf(%d, &num);

    Read a character:char ch;items_read = scanf(%c, &ch);

    Read a string of max length, 79 chars:char buf[80];buf[79]=\0; // Ensure a terminating NULL.items_read = scanf(%79s, buf);

    Read number after pattern of a::int num;items_read = scanf(a:%d, &num);always check the return value of scanf

  • I/O C++-styleBasic classes:iostream (cout, cin, cerr)ostringstream, istringstreamC++-style IO is easier for simple stuffcout
  • I/O C++-style continued...printf(%.3f rounded to 2 decimals is %.2f\n, 2.325, 2.325); becomes


  • C and C++ I/O comparedC-style I/O:No type safety. What happens with printf(%d, c);?Conversion specifications have a high learning curve.Almost all the state of the I/O is contained in the function call.

    C++ style I/O: Manipulators are very verbose/annoying Global state gets changed. When you do cout

  • Multiple File DevelopmentEach file is considered a moduleThere is no enforced relation between the filename and its contents!Related functions and variables can be grouped into different filesint add(int a, int b);

    int main(void) {int result;printf(%d\n, add(a,b));return 0;}

    int add(int a, int b) {return a + b;}

    int sub(int a, int b) {return a - b;}main.ccutils.cc

  • The compilation ProcessPreprocessor.c.h.c.hCompilerLinkerexecutableLibrariesSource code (text)C/C++ code (text)Object code (bin)Native Executable (bin)PreprocesserResolves #define, #includeCompilerTranslates code to Machine Language. It outputs an object file. This code is not executableLinkerTakes object files and resolves references to functions and variables in different files

  • Compilation in UnixThe following commands perform the whole compilation process for C and C++:gcc -Wall -g file1.c file2.c -o prognameg++ -Wall -g file1.cc file2.cc -o progname

    You can control which stages get run:Only run the preprocessorgcc -E file.cOnly run the compiler (dont link)gcc -Wall -ansi -c file.cLink these filesgcc file1.o file2.o -o progname

  • Common Compilation options-Wall enable all warnings-ansi turn on strict ansi compliance-v verbose mode on. (lists which directories were searched for include files and libraries)-g generate debugging symbols-c compile only (create object file)-E run the preprocessor only-s generate assembly code (instead of object code)-I prepend directory to include path-L prepend directory to library path-l library to link (looks for lib.so, or .a, or .la) in library path-o specifies output filename-O[n] specifies optimization level (default 0)-D[=value] define the give preprocessor TagAlways specify -Wall and -g: gcc -Wall -g

  • Preprocessor and CompilerPreprocessorDoes not understand C/C++Produces text that gets read by the compiler

    CompilerExpects pure C/C++ (no preprocessor stuff)Checks syntaxTypechecks your codeGenerates, and optimizes, machine codeProduces object files for the linkerStill knows what source file and line numbers

  • LinkerLinkerResolves dependencies between object files Places functions, variables, in final locationGenerates executablesDoes no code optimizationKnows nothing about source files (filenames or line numbers)Knows nothing about typesMatches dependencies by name aloneIn C++, linker symbols have been mangled by the compiler (name mangling) to include the return type and argument types. This allows for overloading.Name mangling is compiler dependent. The linker may not be able to link objects from different compilers.

  • Object FilesObject files contain compiled code plus an index stating what symbols it has, and what symbols it needs

    Use nm (unix) and dumpbin (windows) to list the index

    The linker look at all the the object files and tries to find a one-to-one mapping of needs symbol to a has symbol

    .dll and .so files (windows and unix respectively) are object files with special indexes that the OS can understand and use at runtime.

    Object File extensions: .o, .obj

  • Identify who gave the errorError 1:test.c:1:10: #include expects "FILENAME" or

    Error 2:/tmp/ccdoe7a7.o: In function `main':/tmp/ccdoe7a7.o(.text+0x7): undefined reference to `foo'collect2: ld returned 1 exit status

    Error 3:test.c: In function `main':test.c:4: `iii' undeclared (first use in this function)test.c:4: (Each undeclared identifier is reported only oncetest.c:4: for each function it appears in.)test.c:4: parse error before `989'

    Error 4:/tmp/ccwltu5R.o: In function `foo':/tmp/ccwltu5R.o(.text+0x0): multiple definition of `foo'/tmp/ccx3bPfI.o(.text+0x0): first defined herecollect2: ld returned 1 exit status

  • BreakStand upStretchPlay with stuff animals

    Next topics:Header FilesPreprocessor

  • Header FilesCommon Usages:Creates an informal module interface (No relation to Java i