multiple files and beyond cop 3275 – programming using c

74
Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Upload: mervin-parker

Post on 13-Jan-2016

215 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Multiple Files and beyondCOP 3275 – PROGRAMMING USING C

Page 2: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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 7th.

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!

Page 3: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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)

Page 4: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

#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

Page 5: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Example

int ReadNumberOfMines(int min, int max) {

int mines = -1;

while (mines < min || mines > max) {

printf("Please input the number of mines: ");

scanf("%i", &mines); getchar();

if(mines < min || mines > max) {

printf("The number of mines must be positive and less than %d\n", TOTAL_TILES);

}

}

return mines;

}

Page 6: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Example

int ReadNumberOfMines(int min, int max) {

int mines = -1;

while (mines < min || mines > max) {

printf("Please input the number of mines: ");

scanf("%i", &mines); getchar();

if(mines < min || mines > max) {

printf("The number of mines must be positive and less than %d\n", TOTAL_TILES);

}

}

return mines;

}

Page 7: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Example

int ReadNumberOfMines(int min, int max) {

#define MINE_VALID mines < min || mines > max

int mines = -1;

while (mines < min || mines > max) {

printf("Please input the number of mines: ");

scanf("%i", &mines); getchar();

if(mines < min || mines > max) {

printf("The number of mines must be positive and less than %d\n", TOTAL_TILES);

}

}

return mines;

}

Page 8: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Example

int ReadNumberOfMines(int min, int max) {

#define MINE_VALID mines < min || 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;

}

Page 9: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Example

int ReadNumberOfMines(int min, int max) {

#define MINE_VALID mines < min || 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

}

Page 10: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

The compilation process

source.c

Preprocessor

Unlinked Machine

Code

“Preprocessed”Source Compiler

a.out (Binary file)

Linker

Page 11: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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?

Page 12: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

The linker

Well… many reasons!

For now compilation seems like a really fast process, right? Only a few seconds.

However…..

Taken from XKCD

Page 13: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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.

Page 14: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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.

Page 15: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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.

Page 16: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 17: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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)

Page 18: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Function Pointers

Page 19: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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.

Page 20: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

<some content>

}function

Page 21: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

<some content>

}<some

conent>function

Page 22: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 23: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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?

Page 24: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 25: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 26: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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?

Page 27: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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.

Page 28: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Declaring my function pointer so that I can call the function

<return type> (*<pointerName>)(<params>) = <function name>;

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;

Page 29: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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!

Page 30: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

More on function pointers

Page 31: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Admin stuff

Quiz today is last in class.

Next week:

A bit on types

Closing up some topics I’ve mentioned

Class on August 7th 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?

Page 32: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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.

Page 33: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Back to function pointers

Remember when we closed last Wednesday:

struct student{char *name;int UFID;int year;

struct student *next;

};

Page 34: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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;

}

}

}

Page 35: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Finishing Function Pointers and Advanced Types8/3/2015

Page 36: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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.

Page 37: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Back to function pointers

Remember when we closed last Friday:

struct student{char *name;int UFID;int year;

struct student *next;

};

Page 38: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 39: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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;

}

}

}

Page 40: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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;

}

}

}

Page 41: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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;

}

}

}

Page 42: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 43: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 44: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 45: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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!

Page 46: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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.

Page 47: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Creating an enum

enum <name> { <options> };

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

Page 48: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Unions, binary operations and our last official lecture8/5/2015

Page 49: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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!

Page 50: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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;

Page 51: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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.

Page 52: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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.

Page 53: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Typedef and structs

typedef struct S {

//variables

} T;

Can be converted to:

struct S {

//variables

};

typedef struct S T;

Page 54: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Typedef and structs

typedef struct S {

//variables

} S;

Can be converted to:

struct S {

//variables

};

typedef struct S S;

Page 55: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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.

Page 56: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 57: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 58: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 59: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Union

union <identifier> {

<types>

};

union U {

int i;

float f;

};

Page 60: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 61: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

You can also typedef them!

typedef union U {

int i;

float f;

} U;

Same rules that we discussed earlier for structs.

Page 62: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

Binary operations

Page 63: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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.

Page 64: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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.

Page 65: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 66: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

0

_Bool flag = FALSE;

Page 67: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

1

_Bool flag = TRUE;

Page 68: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

- - - - - - - 1

_Bool flag = TRUE;

Page 69: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

- - - - - - - 1

- - - - - - - 1

_Bool flag = TRUE;

_Bool flag2 = TRUE;

Page 70: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

- - - - - - - 1

- - - - - - - 1

_Bool flag = TRUE;

_Bool flag2 = TRUE;

Page 71: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

- - - - - - 1 1

int flags = 3;

Wait… why 3?

27 26 25 24 23 22 21 20

Page 72: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

27 26 25 24 23 22 21 20

Page 73: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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

Page 74: Multiple Files and beyond COP 3275 – PROGRAMMING USING C

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;