Functions Separate Compilation

Slides:



Advertisements
Similar presentations
CSE 303 Lecture 16 Multi-file (larger) programs
Advertisements

CSc 352 An Introduction to the C Preprocessor Saumya Debray Dept. of Computer Science The University of Arizona, Tucson
Software Development Method. Assignments Due – Homework 0, Warmup Reading – Chapter 2 –
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 10: Appendices.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction 13.2The #include Preprocessor Directive 13.3The.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
 2007 Pearson Education, Inc. All rights reserved C Preprocessor.
Computer Science 210 Computer Organization Introduction to C.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 12 - The Preprocessor Directives (Macros)
C Programming Functions Macros. Functions vs. Methods Java classes include methods which can be called from any code with appropriate access (recall public.
C Programming Functions Program Organization Separate Compilation.
Structure of a C program Preprocessor directive (header file) Program statement } Preprocessor directive Global variable declaration Comments Local variable.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Compilation & Linking Computer Organization I 1 November 2009 © McQuain, Feng & Ribbens The Preprocessor When a C compiler is invoked, the.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.
Makefiles. Multiple Source Files (1) u Obviously, large programs are not going to be contained within single files. u C provides several techniques to.
Separate Compilation make and makefiles
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
C Programming Separate Compilation Variable Lifetime and Scope make.
Lecture-3 Functions and Recursion. C Preprocessor Includes header files like stdio.h Expands macros defined Handles conditional compilations PreprocessorProcessor.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction 13.2The #include Preprocessor Directive 13.3The.
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
1 Building a program in C: Preprocessor, Compilation and Linkage.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
C Programming Functions Separate Compilation. Functions vs. Methods Java classes include methods which can be called from any code with appropriate access.
13 C Preprocessor.
ECE 382 Lesson 20 Lesson Outline Structs Functions Headers Example
Chapter VII: Arrays.
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
User-Written Functions
Computer Science 210 Computer Organization
Chapter 1.2 Introduction to C++ Programming
A bit of C programming Lecture 3 Uli Raich.
Introduction to C++ Systems Programming.
C Programming Tutorial – Part I
Chapter 13 - The Preprocessor
Chapter 5 Function Basics
Introduction to C Topics Compilation Using the gcc Compiler
The Preprocessor Based on Chapter 1 in C++ for Java Programmers by Weiss When a C compiler is invoked, the first thing that happens is that the code is.
Pre-processor Directives
User-Defined Functions
Programming in C Input / Output.
Computer Science 210 Computer Organization
FUNCTIONS WITH ARGUMENTS
User Defined Functions
Functions.
Register Variables Declaring a variable as a "register" variable is an advisory to the compiler to keep the normal location of the variable in a register,
C Preprocessor(CPP).
Comments, Prototypes, Headers & Multiple Source Files
Introduction to C Topics Compilation Using the gcc Compiler
Classes and Objects.
Programming in C Miscellaneous Topics.
CSc 352 An Introduction to the C Preprocessor
Programming in C Miscellaneous Topics.
Functions.
Introduction to C Topics Compilation Using the gcc Compiler
C Preprocessor Seema Chandak.
Functions Extra Examples.
What Is? function predefined, programmer-defined
Variables in C Topics Naming Variables Declaring Variables
Compiler vs linker The compiler translates one .c file into a .o file
Functions, Part 2 of 42 Topics Functions That Return a Value
CPS125.
Preprocessor Directives and Macros Chapter 21
Presentation transcript:

Functions Separate Compilation C Programming Functions Separate Compilation

Functions vs. Methods Java classes include methods which can be called from any code with appropriate access (recall public methods) C functions are like Java methods, but they don’t belong to any class. Functions are defined in a file and may be either global to your program or local to (“private” in) the file in which they are defined*. Like Java methods, C functions Have a name Have a return type May have parameters Unlike Java methods, a function in C is uniquely identified by its name. Therefore, there is no concept of method overloading in C as there is in Java. There can be only one main( ) function in a C application. Our standards dictate that function names begin with and UPPERCASE letter

Arguments vs Parameters A parameter is defined in the function definition. It is a place holder for the argument during function execution void PrintInt( int n ) // n is the parameter { printf( “%20d\n”, n); } An argument is a value passed to a function when the function is called int age = 42; PrintInt( age ); // age is the argument These terms are often (incorrectly) used interchangeably, but the context is usually clear

Passing Arguments Primitive types (int, char, float, etc) are passed to function “by value” A copy of the argument is passed to the function Changing the parameter within the function has no effect on the argument in the calling code Arrays are passed “by reference” A copy of the address of the array is passed to the function The parameter is an “alias” for the argument References to array elements in the function also refer to array elements in the calling code

Passing Arguments /* ages.c */ #include <stdio.h> void GrowOlder( int a[ ], int size) { int k; for (k = 0; k < size; k++) ++a[ k ]; } int AvgAge( int array[ ], int size) int k, sum = 0; sum += array[ k ]; return sum / size; int main( ) { int nrStudents = 6; int ages[ 6 ] = {19, 18, 17, 22, 44, 55}; GrowOlder( ages, nrStudents ); int avgAge = AvgAge( ages, nrStudents ); printf(“The average age is %d\n”, ageSum); return 0;

Passing 2-D Arrays Passing a 2-d array to a function is similar to passing a 1-d array Basic function prototype void PrintChessBoard( char [ 8 ][ 8 ] theBoard); Calling the function char chessBoard[ 8 ] [ 8 ]; PrintChessBoard( chessBoard ); As we will see, the compiler needs to know the size of each row, but not the number of rows. This allows an alternative prototype void PrintChessBoard( char[ ] [ 8 ] theBoard );

A Simple C Program /* sample.c */ #include <stdio.h> typedef double Radius; #define PI 3.1415 /* given the radius, calculates the area of a circle */ double CircleArea( Radius radius ) { return ( PI * radius * radius ); } // given the radius, calcs the circumference of a circle double Circumference( Radius radius ) return (2 * PI * radius ); int main( ) Radius radius = 4.5; double area = CircleArea( radius ); double circumference = Circumference( radius ); printf (“Area = %10.2f, Circumference = %10.2f\n”, area, circumference); return 0;

Function Reuse The functions CircleArea and Circumference are general functions that may be used by multiple applications. To make them available to multiple applications, we must place them into a separate .c file However, recall that the compiler requires that we must provide the function prototypes to the calling code. We do this by placing the prototypes and supporting declarations into a header (.h) file which is then included in .c files that wish to call the functions.

circleUtils.c /* circleUtils.c ** Utilites for circle calculations */ #include “circleUtils.h” #define PI 3.1415 // why not in the .h file?? /* given the radius, calculates the area of a circle */ double CircleArea( Radius radius ) { return ( PI * radius * radius ); } // given the radius, calcs the circumference of a circle double Circumference( Radius radius ) return (2 * PI * radius );

circleUtils.h A header (.h) file contains everything necessary to compile a .c file that includes it /* circleUtils.h*/ // #includes required by the prototypes, if any /* supporting typedefs and #defines */ typedef double Radius; /* function prototypes */ // given the radius, returns the area of a circle double CircleArea( Radius radius ); // given the radius, calcs the circumference of a circle double Circumference( Radius radius );

Sample Code Revisited /* sample.c */ #include <stdio.h> #include “circleUtils.h” int main( ) { Radius radius = 4.5; double area = CircleArea( radius ); double circumference = Circumference( radius ); printf (“Area = %lf, Circumference = %lf\n”, area, circumference); return 0; }

Header Files When a file contains functions to be reused in several programs, their prototypes and important #defines and typedefs are placed into a header ( .h ) that is then included where needed. Each .h file should be “stand alone”. That is, it should declare any #define and typedef needed by the prototypes and #include any .h files it needs to avoid compiler errors. The .h file should contain everything needed to successfully compile any .c file that includes it. In this example, the prototypes for CircleArea() and Circumference( ) are placed into the file circleUtils.h which would then be included in circleUtils.c and any other .c file that uses CircleArea( ) and / or Circumference( ).

Guarding Header Files Because a .h file may include other .h files, there is the possibility that one or more .h files may unintentionally be included in a single .c file more than once, leading to compiler errors (multiple name definitions). To avoid these errors, .h files should be “guarded” using the compiler directives #ifndef (read as “if not defined”) and #endif Other compiler directives for conditional compilation include #ifdef read as “if defined” #else #elif read as “else if”

Guarded circleUtils.h #ifndef CIRCLEUTIL_H #define CIRCLEUTIL_H /* include .h files as necessary */ /* supporting typedefs and #defines */ typedef double Radius; /* function prototypes */ // given the radius, returns the area of a circle double Area( Radius radius ); // given the radius, calcs the circumference of a circle double Circumference( Radius radius ); #endif

Compiling and linking When a program’s code is separated into multiple .c files, we must compile each .c file and then combine the resulting .o files to create an executable program. The files may be compiled separately and then linked together. The -c flag in the first two command tells gcc to “compile only” which results in the creation of .o (object) files. In the 3rd command, the presence of the.o extension tells gcc to link the files into an executable gcc -c -Wall circleUtils.c gcc -c -Wall sample.c gcc -Wall -o sample sample.o circleutils.o Or if there only a few files, compiling and linking can be done all in one step gcc -Wall -o sample sample.c circleUtils.c 1/20/10

Recursion C functions may be called recursively. Typically a function calls itself A properly written recursive function has the following properties A “base case” - a condition which does NOT make a recursive call because a simple solution exists A recursive call with a condition (usually a parameter value) that is closer to the base case than the condition (parameter value) of the current function call Each invocation of the function gets its own set of arguments and local variables We’ll see how recursion is implemented later

Recursion Example /* print an integer in decimal ** K & R page 87 (may fail on largest negative int) */ #include <stdio.h> void printd( int n ) { if ( n < 0 ) printf( “-” ); n = -n; } if ( n / 10 ) /* (n / 10 != 0) -- more than 1 digit */ printd( n / 10 ); /* recursive call: n has 1 less digit */ printf( “%c”, n % 10 + ‘0’); /* base case --- 1 digit */

Recursive Exercise Complete the following recursive function that sums all of the integers from 1 to N int SumToN( int N ) { if (____________________) // base case return N; else // recursive call return ______________________; }

Inline Functions C99 only Short functions may be defined as “inline”. This is a suggestion to the compiler that calls to the function should be replaced by the body of the function. inline functions provide code structure and readability and (may) increase performance inline bool isEven( int n ) { return n % 2 == 0; } inline max( int a, int b ) { return a > b ? a : b; }

Macros C provides macros as an alternative to small functions. More common prior to C99 (inline functions are better) Handled by the preprocessor Several “gotcha”s Inline functions are usually better General macro format. #define NAME( params if any ) code here Note: there is NO space between the name and the left paren

SQUARE( ) A simple macro to square a variable #define SQUARE( x ) (x * x) Like all #defines, the preprocessor performs text substitution. Each occurrence of the parameter is replaced by the argument text. int y = 5; int z = SQUARE( y ); But now consider this statement int w = SQUARE( y + 1 );

A better SQUARE( ) This version is better #define SQUARE( x ) ( (x) * (x) ) int y = 5; int z = SQUARE( y ); int w = SQUARE( y + 1 ); But still doesn’t work in every case int k = SQUARE( ++y );