Presentation is loading. Please wait.

Presentation is loading. Please wait.

Multiple Files and beyond COP 3275 – PROGRAMMING USING C.

Similar presentations


Presentation on theme: "Multiple Files and beyond COP 3275 – PROGRAMMING USING C."— Presentation transcript:

1 Multiple Files and beyond COP 3275 – PROGRAMMING USING C

2 Administrative stuff  Quiz this Friday! Last in class quiz  Remember last Quiz will be takehome  Homework #5 will be graded this week  Homework #6 was assigned on Saturday  Due August 7 th.  Hangman  Three files: main.c dict.c gameplay.c  Extra credit: 10%  Will be graded by me! (Rahul will be grading the Quiz)  Remember we have a 5% of class participation. If you have a pretty decent idea that I don’t know your name and/or face. Be sure to talk to me in these next couple of weeks. You don’t have to be super vocal to get that grade, but at least have come to a good number of clases and be sure I know who you are. You don’t want that grade to catch you off guard!

3 What are we covering the last two weeks?  Conclude the preprocessor stuff  Talk about multiple code files and linking  Pointers to functions (Wednesday-Friday)  Next week advanced types (enums, unions, typedef)

4 #undef  The use we did last time was very very awkward.  The best reason to use it is for your own macros.  If you are working on a team of programmers, you might want a quick macro to do something but you don’t want it to affect others.  You can always undefine your own macros after you are done u

5 Example int ReadNumberOfMines ( int min, int max ) { int mines = - 1 ; while ( mines max ) { printf ( "Please input the number of mines: " ); scanf ( "%i", & mines ); getchar (); if( mines max ) { printf ( "The number of mines must be positive and less than %d\n", TOTAL_TILES ); } return mines ; }

6 Example int ReadNumberOfMines ( int min, int max ) { int mines = - 1 ; while (mines max) { printf ( "Please input the number of mines: " ); scanf ( "%i", & mines ); getchar (); if(mines max) { printf ( "The number of mines must be positive and less than %d\n", TOTAL_TILES ); } return mines ; }

7 Example int ReadNumberOfMines ( int min, int max ) { #define MINE_VALID mines max int mines = - 1 ; while (mines max) { printf ( "Please input the number of mines: " ); scanf ( "%i", & mines ); getchar (); if(mines max) { printf ( "The number of mines must be positive and less than %d\n", TOTAL_TILES ); } return mines ; }

8 Example int ReadNumberOfMines ( int min, int max ) { #define MINE_VALID mines max int mines = - 1 ; while ( MINE_VALID ) { printf ( "Please input the number of mines: " ); scanf ( "%i", & mines ); getchar (); if( MINE_VALID ) { printf ( "The number of mines must be positive and less than %d\n", TOTAL_TILES ); } return mines ; }

9 Example int ReadNumberOfMines ( int min, int max ) { #define MINE_VALID mines max int mines = - 1 ; while ( MINE_VALID ) { printf ( "Please input the number of mines: " ); scanf ( "%i", & mines ); getchar (); if( MINE_VALID ) { printf ( "The number of mines must be positive and less than %d\n", TOTAL_TILES ); } return mines ; #undef MINE_VALID }

10 The compilation process source.c Preprocessor Unlinked Machine Code “Preprocessed” Source Compiler a.out (Binary file) Linker

11 The linker  Let’s first see a linking error! *.c:(.text+0x15): undefined reference to `my_function' collect2: error: ld returned 1 exit status  Essentially, that is telling us that ‘my_function’ was used but never defined.  The compiler doesn’t need to know that all the functions and variables exist, it can leave some of those references to be resolved by the linker.  Why?

12 The linker  Well… many reasons!  For now compilation seems like a really fast process, right? Only a few seconds.  However….. Taken from XKCD

13 The linker  Very quickly programmers realized that big programs took a long time to compile  They also realized small changes in a project were causing us to recompile the whole code base (so inefficient)  Programmers are engineers… Engineers hate inefficiencies…  So, very smart people realized that if we compartmentalize our code into modules, and change code only in one module. We don’t need to compile EVERY single module, but just the one that has changes.

14 Compiling without linking  Gcc has a flag to prevent linking!  -c  gcc –c *.c  Generates a.o file (unlinked machine code file)  Later we can compile multiple o files into an executable.  Let’s test it out.

15 Extern  All of our global variables have been external.  That means that other modules (files with code) could access them if they knew what the name is.  We could write: extern int i;  In another module, and access the global variable defined in the other file.

16 Static  We can use static to protect a global variable from being accessed by another module. static int i;  Both static and extern can be used for functions too (extern being the default).

17 Header files  Made out of declarations (but no definitions)  Extension: *.h  We can use include to add them. #include “myheader.h”  Notice “” instead of <>  “” user defined (look for them in current folder)  <> system defined (look for them in common include folders)

18 Function Pointers

19 Administrative Stuff  Quiz #7 and #8 grades were released Monday.  We are currently working on the grading of Homework #5, still hoping to have it ready by the end of the week.  Quiz #9 (will be themed… but more on that later)  Theory question on multiple files (static, extern, compilation)  Theory question on function pointers  Follow code and provide output with function pointers  Actual dictionary for Homework #6 will have about 10000 words, will be released likely tonight.

20 Function pointers  Calling functions without knowing their name….  A pointer can point to anything in memory.  That includes: code!  Actually, at it’s core every function we have written has been a pointer to a piece of code! int function(void) { } function

21 Function pointers  Calling functions without knowing their name….  A pointer can point to anything in memory.  That includes: code!  Actually, at it’s core every function we have written has been a pointer to a piece of code! int function(void) { } function

22 Let’s differentiate concepts related to functions  Declaration int duplicate(int a);  Definition int duplicate(int a) { return 2*a; }  Call to the function (execution) duplicate(30);  Pointer!! duplicate

23 A common mistake that I’ve seen in a few of your pieces of code…  Let’s say we defined a function _Bool HasWon(void) ;  I saw a few people then say something like this: if(HasWon) { printf(“You won”); }else { printf(“Next play”); }  What is wrong with that? Does it hit the if or the else?

24 A common mistake that I’ve seen in a few of your pieces of code…  Let’s say we defined a function _Bool HasWon(void) ;  I saw a few people then say something like this: if(HasWon) { printf(“You won”); }else { printf(“Next play”); }  What is wrong with that? Does it hit the if or the else? Call to the function (execution) duplicate(30); Pointer!! duplicate

25 A common mistake that I’ve seen in a few of your pieces of code…  Let’s say we defined a function _Bool HasWon(void) ;  I saw a few people then say something like this: if(HasWon) { printf(“You won”); }else { printf(“Next play”); }  What is wrong with that? Does it hit the if or the else? Call to the function (execution) duplicate(30); Pointer!! duplicate

26 A common mistake that I’ve seen in a few of your pieces of code…  Let’s say we defined a function _Bool HasWon(void) ;  I saw a few people then say something like this: if(HasWon () ) { //those are important! printf(“You won”); }else { printf(“Next play”); }  What is wrong with that? Does it hit the if or the else?

27 Ok so with the name I get a pointer… what’s it’s type?  I’ve mentioned that void* as a type can hold anything.  This is still true, but you can’t do much if you save it in a void* void *funct = duplicate;  That compiles… (as long as duplicate is the name of a function) but we can’t call the function.

28 Declaring my function pointer so that I can call the function  (* )( ) = ;  How do I remember that? How do I eat it? (That’s such a Hispanic saying lol)  Hopefully by now the declaration of a function is familiar to you: int duplicate(int a);  If you want a pointer to that function, you wrap the name in parenthesis and add the * int (*duplicate)(int a);  Then you give your pointer a name: int (*pointer)(int a);  Then you assign it a functions name: int (*pointer)(int a) = duplicate;

29 Adding a type that can hold that  There is a special keyword for defining new types.  We will talk a lot more about it next week  typedef  In our case: typedef int (*math_funct)(int a);  Then we could do: math_funct dup = duplicate;  Let’s actually do a fun exercise now!

30 More on function pointers

31 Admin stuff  Quiz today is last in class.  Next week:  A bit on types  Closing up some topics I’ve mentioned  Class on August 7 th will be non-mandatory, but I’ll be there in case you have questions about the homework or take home quiz.  Posted dictionaries for Homework 6.  Any questions?

32 A quick word about multiple files  Some times we need to forward declare functions that are defined in other files.  The linker needs to make an educated guess on what the function is going to be returning  This is where header files become really useful  Let’s take a look at this with an example.

33 Back to function pointers  Remember when we closed last Wednesday: struct student{ char *name; int UFID; int year; struct student *next; };

34 Sorted add struct student * add ( struct student * head, char * name ); struct student * add ( struct student * head, char * name ) { if( head == NULL) { return newStudent ( name ); }else { if(strcmp(head->name, name) > 0 ) { struct student * s = newStudent ( name ); s -> next = head ; return s ; }else { head -> next = add ( head -> next, name ); return head ; }

35 Finishing Function Pointers and Advanced Types 8/3/2015

36 Administrative stuff  Quiz will be posted by Wednesday morning.  It will cover stuff from today and Wednesday.  Both the last quiz and homework are due on midnight on 8/7.  Class on 8/7 is optional, will answer questions on quiz and homework, but likely will just hangout, no particular plan.  As a reminder: You are allowed to discuss homework projects with each other, and learn from each other, even help debug each other’s program. But in the end, the solutions to the homework and quiz need to be your own.  I will post preliminary class participation grades tonight. Please check Canvas, and if you have questions let me know. I reserve the right to change those grades until the end of the week.

37 Back to function pointers  Remember when we closed last Friday: struct student{ char *name; int UFID; int year; struct student *next; };

38 We created three comparison functions int compare_year ( struct student * a, struct student * b ); int compare_UFID ( struct student * a, struct student * b ); int compare_name ( struct student * a, struct student * b ); typedef int (* compare_fun )( struct student * a, struct student * b );

39 Original sorted add struct student * add ( struct student * head, char * name ); struct student * add ( struct student * head, char * name ) { if( head == NULL) { return newStudent ( name ); }else { if(strcmp(head->name, name) > 0 ) { struct student * s = newStudent ( name ); s -> next = head ; return s ; }else { head -> next = add ( head -> next, name ); return head ; }

40 Sorted add struct student * add ( struct student * head, struct student s); struct student * add ( struct student * head, struct student s) { if( head == NULL) { return s; }else { if( strcmp(head->name, s->name) > 0 ) { s -> next = head ; return s ; }else { head -> next = add ( head -> next, s); return head ; }

41 Sorted add struct student * add ( struct student * head, struct student s, compare_fun f); struct student * add ( struct student * head, struct student s, compare_fun f) { if( head == NULL) { return s ; }else { if( f (head, s) > 0 ) { s -> next = head ; return s ; }else { head -> next = add ( head -> next, s ); return head ; }

42 Functions we have int compare_year ( struct student * a, struct student * b ); int compare_UFID ( struct student * a, struct student * b ); int compare_name ( struct student * a, struct student * b ); typedef int (* compare_fun )( struct student * a, struct student * b ); struct student * newStudent ( char * name, int UFID, int year ); struct student * add ( struct student * head, struct student s, compare_fun f);

43 Use struct student * s1 = newStudent ( " Andrew ", 12345678, 3 ); struct student * s2 = newStudent ( "Juliana", 23456789, 1 ); struct student * s3 = newStudent ( "Ana", 31234578, 2 ); struct student * list = NULL; compare_fun f ; //we just need to assign it list = add ( list, s1, f ); list = add ( list, s2, f ); list = add ( list, s3, f );

44 So what we know so far.  Enough to understand most C programs.  We have covered:  Basic structure  Types  Variables  Operators  Input/Output  Conditionals  Loops  Arrays  Structures  Functions  Pointers  Pointer arithmetic  Reading and Writing Files  Command line arguments  Preprocessor and constants  Modules and linking  Functions pointers

45 Advanced types  Let’s start with Enumerations!  Finite sets of concepts that we can give some order to.  What sort of things do we enumerate?  Colors  Months  Seasons  School semesters  States of the USA  State of a system/program  Countries  Many more!

46 What would we do right now?  Let’s say with months.  Two options:  Create a variable/constant for each month.  Just come up with a good coding scheme (maybe just using an int) and working around it.  Enums are the best of both worlds.

47 Creating an enum  enum { };  enum month { January, February, March, April, May, June, July, August, September, October, November, December };  enums in C are mostly just ints.  By default, the first element takes the value of 0. The other elements increase by 1.  We can force an element to have a particular value!  enum month { January = 1, February, March, April, May, June, July, August, September, October, November, December };

48 Unions, binary operations and our last official lecture 8/5/2015

49 Admin stuff  Homework 5 grades released  If you have issues with any grades! Contact Rahul and me ASAP.  Quiz is posted! As usual: no late policy for quizzes. Turn in by 11:59pm on Friday.  Homework 6 due at the same time.  If you are doing extra credit, please add a comment about it.  If you are considering a late submission, please let me know.  Reminder about instructor evaluations!

50 Typedef and structs  On Monday, we were talking about ‘typedefing’structs. typedef struct S { //variables } T ;  This allows to write ‘T’ as a type instead of ‘struct S’  T and S could be the same (actually in most cases they will be: typedef struct S { //variables } S ;

51 Typedef and structs typedef struct S { //variables } T ;  Actually, the identifiers S and T get “saved” in different places by the compiler.  For example when we do: struct S { //variables };  We can still use S as the name of a variable or a function.  This is because S is bound as a struct identifier, and not an identifier for a function or variable.

52 Typedef and structs  However!  T in: typedef struct { //variables } T ;  Is bound in the same domain of names used by variable and function identifiers.  That means there can be a variable name T, or a function named T.  The names collide and on compilation we would get a redefinition error.

53 Typedef and structs typedef struct S { //variables } T ;  Can be converted to: struct S { //variables }; typedef struct S T ;

54 Typedef and structs typedef struct S { //variables } S ;  Can be converted to: struct S { //variables }; typedef struct S S ;

55 Typedef and structs  That means that if we have: typedef struct S { //variables } T ;  S is only defined as being bound to the struct (it only exists as “struct S”) while T exists by itself.  ‘struct S’ and ‘T’ still refer to the same type though  What are the practical implications?  Very little. Both are the same.  Typedef saves you some typing in general, but collides with variable names  Certain forward declarations (before defining the struct) can be done using the struct S notation.

56 Unions  A union is a special data type.  Allows us to store different types using the same address in memory.  In some ways, it brings two or more types together.  If you think of types as sets (like the mathematical definition of a set) the name union makes a lot of sense. A B

57 Unions  A union is a special data type.  Allows us to store different types using the same address in memory.  In some ways, it brings two or more types together.  If you think of types as sets (like the mathematical definition of a set) the name union makes a lot of sense. A U B

58 Unions  Sometimes we have a variable but don’t quite know the actual type.  For example:  it could be a string or a number.  It could be an integer or a float.  In other instances we have a variable, and we want to be able to interpret it’s binary value as a different type.  Many modern programming languages provide “mutable types” which essentially are very smart unions

59 Union union { }; union U { int i ; float f ; };

60 Unions union U { int i ; float f ; };  Only one of the types can be used at the time.  They all refer to the same memory location! union U data ; data. i = 10 ; printf ( "%f\n", data. f );

61 You can also typedef them! typedef union U { int i ; float f ; } U ;  Same rules that we discussed earlier for structs.

62 Binary operations

63 The logical or and and  We have mentioned before:  || logical or  && logical and  That means if we have multiple Booleans we can check:  if all of them are true (using an and); or  if at least one of them is true (using an or).  Or many other logical questions if we combine them  Those take the same philosophy than if and conditionals:  0 is false, everything else is true.  What the result is only matters if it is true or false.

64 Bitwise binary operations  Will this be useful?  If you are CEN, EE or CSE: yes, if you ever work with any microprocessor.  If not, then sorry lol  Well _Bool (or bool) variables are actually integers  An integer is 4 bytes.  And a Boolean is literally using one bit.  We could potentially use that memory more efficiently and save 4*8 Booleans (might need a bit more code to do it though)  Thankfully, bitwise operations are really fast.

65 Bitwise operators  | bitwise or. (e.g. 010 | 110 = 110)  & bitwise and (e.g. 010 &110 = 010)  ^ bitwise xor (exclusive or) (e.g. 010 ^ 110 = 100)  ~ not (one’s complement) (e.g. ~010 = 101)  >> bitwise right shift  << bitwise left shift

66 0 _Bool flag = FALSE;

67 1 _Bool flag = TRUE;

68 -------1

69 -------1-------1 _Bool flag2 = TRUE;

70 -------1-------1 _Bool flag = TRUE; _Bool flag2 = TRUE;

71 ------11 int flags = 3; Wait… why 3? 2727 2626 2525 2424 23232 2121 2020

72 How do we access that? int flags = 3 ; if( flags & 2 ) { }  Because 2 is  00000010  And our flag has a value of 3  00000011  The & (bitwise and) results in  00000010 &  00000011  00000010 ------ 1 1 2727 2626 2525 2424 23232 2121 2020

73 How do I set it?  If you want to set it to 1:  flags | = 2 ;  If you want to set it to 0:  flags & = ~( 2 );

74 Even better!!! This is where things get sexy…  If x is the number of bit we want to modify….  Set to 1:  flags | = 1 << x ;  Clear (set to 0):  flags & = ~(1 << x) ;  Toggle:  flags ^ = 1 << x ;  Check bit:  Bit = ( flags >> x ) & 1;


Download ppt "Multiple Files and beyond COP 3275 – PROGRAMMING USING C."

Similar presentations


Ads by Google