Separate Compilation make and makefiles

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
Programming In C++ Spring Semester 2013 Lecture 2 Programming In C++, Lecture 2.
Separate compilation Large programs are generally separated into multiple files, e.g. tuples.h, ray.h, ray.c, tuples.c main.c With several files, we can.
Chapter 7: User-Defined Functions II
Lecture 2 Introduction to C Programming
Introduction to C Programming
1 CS 161 Introduction to Programming and Problem Solving Chapter 9 C++ Program Components Herbert G. Mayer, PSU Status 10/20/2014.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
Guide To UNIX Using Linux Third Edition
CMSC 104, Version 9/011 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program 104 C Programming Standards and Indentation.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Chapter 3 Getting Started with C++
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Adv. UNIX: large/131 Advanced UNIX v Objectives of these slides: –learn how to write/manage large programs consisting of multiple files, which.
Programming With C.
Introduction to C Programming CE Lecture 7 Compiler options and makefiles.
Chapter 6: User-Defined Functions
C Programming Functions Program Organization Separate Compilation.
Functions Kernighan/Ritchie: Kelley/Pohl: Chapter 4 Chapter 5.
Homework K&R chapter 4. HW3: ASCII Hex to Integer int axtoi (char s[ ]) { int i, n, flag; n = 0; flag = 1; for ( i = 0; flag; i++) /* for (i = 0; ; i++)
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
1 Programming in C Hello World! Soon I will control the world! Soon I will control the world!
C Tutorial - Program Organization CS Introduction to Operating Systems.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Engineering Computing I Chapter 4 Functions and Program Structure.
Compilation & Linking Computer Organization I 1 November 2009 © McQuain, Feng & Ribbens The Preprocessor When a C compiler is invoked, the.
Algorithms  Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Makefiles. Multiple Source Files (1) u Obviously, large programs are not going to be contained within single files. u C provides several techniques to.
Exam / Homework Exam 1 Starting K&R chapter 4 tonight
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
C Programming Separate Compilation Variable Lifetime and Scope make.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Makefiles CARYL RAHN. Separate compilation Large programs are generally separated into multiple files, e.g. main.c addmoney.c removemoney.c money.h With.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Chapter 6: Function Introduction to function Standard functions User defined functions –function prototype –function definition Function call Storage classes.
Modular Programming. Introduction As programs grow larger and larger, it is more desirable to split them into sections or modules. C allows programs to.
Multiple File Compilation and linking By Bhumik Sapara.
C code organization CSE 2451 Rong Shi. Topics C code organization Linking Header files Makefiles.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
L071 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program Reading Sections
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Programming in C Project Organization Compiler Directives.
C Programming Functions Separate Compilation. Functions vs. Methods Java classes include methods which can be called from any code with appropriate access.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Chapter 9: Value-Returning Functions
The Three Attributes of an Identifier
User-Written Functions
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Functions Separate Compilation
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
Introduction to C Topics Compilation Using the gcc Compiler
Programming in C Miscellaneous Topics.
Programming in C Miscellaneous Topics.
Writing Large Programs
Object Oriented Programming in java
Appendix F C Programming Environment on UNIX Systems
Compiler vs linker The compiler translates one .c file into a .o file
SPL – PS1 Introduction to C++.
Presentation transcript:

Separate Compilation make and makefiles C Programming Separate Compilation make and makefiles

Topics Program organization in multiple files Function and variable scope and lifetime The “make” utility and makefiles

circleUtils.c /* circleUtils.c */ // for function prototypes #include “circleUtils.h” /* ** contains #defines, typedefs, etc used only ** in this .c file */ ** contains code for each callable ** function defined in circleUtils.h

circleUtils.h A header (.h) file contains everything necessary to compile a .c file that #includes it #includes any .h files necessary to compile prototypes Contains #defines and typedefs necessary to compile the prototypes Contains prototypes for circle function available to calling code in other .c files

sample.c /* sample.c */ #include <stdio.h> #include “circleUtils.h” // for prototypes, #defines, etc int main( ) { // code that calls functions whose prototype // are found circleUtils.h return 0; }

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

Compiler vs linker The compiler translates one .c file into a .o file Verifies that all functions are being called correctly Verifies that all variables exist Verifies language syntax The linker combines multiple .o files (and C libraries) to create an executable “Finds” functions called by one .c/.o file, but defined in another E.g. printf( ), scanf( ) “Finds” global variables used by one .c/.o file, but defined in another (more on this soon) Both can be invoked with gcc (see previous lecture)

Program organization main( ) is generally defined in its own .c file and generally just calls helper functions E.g. project1.c Program-specific helper functions in another .c file E.g. proj1Utils.c If there are very few helpers, they can be in the same file as main( ) Reusable functions in their own .c file Group related functions in the same file E.g. circleUtils.c Prototypes, typedefs, #defines, etc. for reusable function in a .h file Same file root name as the .c file. E.g. circleUtils.h

The make Utility Typing out the gcc commands for a project gets less appealing as the project gets bigger. The "make" utility automates the process of compiling and linking. With make, the programmer specifies what the files are in the project and how they fit together. make takes care of the appropriate compile and link steps. make can speed up your compiles since it is smart enough to know that if you have 10 .c files but you have only changed one, then only that one file needs to be compiled before the link step. make has some complex features, but using it for simple things is pretty easy. This slide and those that follow are adapted from Section 2 of “UnixProgrammingTools.pdf” by Nick Parlante, et al at Stanford. Used with permission.

How make works You tell make what files are in your project, how they fit together, how to compile, and how to link them by creating a file that make reads and interprets By default, make looks for a file named either “makefile” or “Makefile” At the Unix console, simply type the command make to compile all necessary files and create a new executable unix> make make can perform other tasks defined in the makefile as well (more on this later)

The makefile A makefile consists of variable definitions, dependency/build rules and comments Comments begin with the ‘#’ character and extend to the end of the line # makefile for project 1 # name, date, etc

The makefile (2) Variable definitions A variable name is defined to represent a string of text, similar to #define in C. They are most often used to represent names of files, directories, and the compiler. Variable are defined simply by setting them to some value (string) The most common variables are typically CC -- the name of your C compiler CFLAGS -- the set of flags that you wish to pass to the compiler LDFLAGS -- the set of flags that you wish to pass to the linker OBJS -- the set of object (.o) files that are linked together to create your executable To use a variable, use the dollar sign ($) followed by the name of the variable in parenthesis or curly braces CC = /usr/local/bin/gcc CFLAGS = -g -Wall $(CC) $(CFLAGS) -c main.c Variables that are not initialized are set to the empty string

The make file (3) A dependency/build rule defines how to make a target based on changes to the files on which the target depends. The order of the rules is irrelevant, except that the first rule is the default rule -- the rule that will be used when make is executed with no arguments A dependency/build rule is made up of two parts A dependency line followed by one or more command lines

The make file (4) Example dependency/build rule sample.o : sample.c circleUtils.h <TAB> $(CC) $(CFLAGS) -c sample.c The first (dependency) line of this rule says that sample.o must be rebuilt whenever sample.c or circleUtils.h changes. Generally a .o file depends on its own .c file and any non-library .h files it #includes. In this example, we would expect that sample.c #includes circleUtils.h The second (command) line tells make how to rebuild sample.o Gotcha -- the command line MUST be indented with a TAB character. Spaces won’t do. This can be a problem when cutting/pasting the contents of a makefile from a terminal screen. Some editors will automatically change a TAB into spaces.

Sample makefile See /afs/umbc.edu/users/c/m/cmsc313/pub/code/makefile

make features The make utility has some built-in default rules. In particular, the default rule for C files is $(CC) $(CFLAGS) -c source-file.c Special syntax can be used to create the list of the .o files OBJS = $(SRCS: .c=.o)

Variable Scope and Lifetime The scope of a variable refers to that part of a program that may refer to the variable. The lifetime of a variable refers to the time in which a variable occupies a place in memory The scope and lifetime of a variable are determined by how and where the variable is defined

static and extern The keyword static is used to Limit the scope of a function or global variable Extend the lifetime of a local variable The keyword extern is used to Inform the compiler that a (global) variable is defined in a different .c file

Function Scope All functions are external because standard C does not allow nesting of function definitions. So no “extern” declaration is needed All functions may be called from any .c file in your program unless they are also declared as static. static functions may only be used within the .c file in which they are defined Their scope is limited

Local variables Local variables are defined within the opening and closing braces of a function, loop, if-statement, etc. (a code “block”) Function parameters are local to the function. Are usable only within the block in which they are defined Exist only during the execution of the block unless also defined as static Initialized variables are reinitialized each time the block is executed if not defined as static static local variables retain their values for the duration of your program. When used in functions, they retain their values between calls to the function.

Global Variables Global (external) variables are defined outside of any function, typically near the top of a .c file. May be used anywhere in the .c file in which they are defined. Exist for the duration of your program May be used by any other .c file in your application that declares them as “extern” unless also defined as static (see below) Static global variables may only be used in the .c file that declares them “extern” declarations for global variables should be placed into a header file

randomInt.c long randomInt; void getRandomInt( int max ) /* a global variable to be used by code in other .c files. ** This variable exists until the program ends ** Other .c files must declare this variable as "extern“ */ long randomInt; /* a function that can be called from any other function ** sets randomInt to a value from 1 to max, inclusive */ void getRandomInt( int max ) { randomInt = getNext( ); } /* a function that can only be called from functions within this file */ static long getNext( ) /* lastRandom is a local variable that can only be used inside this function, but persists between calls to this function */ static long lastRandom = 100001; lastRandom = (lastRandom * 125) % 2796203; return (lastRandom % max) + 1;

randomInt.h #ifndef RANDOMINT_H #define RANDOMINT_H // global variable in randomint.c extern int randomInt; // prototypes for non-static // functions in randomInt.c void getRandomInt( int max ); #endif

variableScope.c - part 1 #include <stdio.h> // extern definition of randomInt and prototype for getRandomInt #include “randomInt.h” /* a global variable that can only be used by functions in this .c file */ static int inputValue; /* a function that can only be called by other functions in this .c file */ static void inputPositiveInt( char prompt[ ] ) { /* init to invalid value to enter while loop */ inputValue = -1; while (inputValue <= 0) printf( "%s", prompt); scanf( "%d", &inputValue); }

variableScope.c - part 2 /* main is the entry point for all programs */ int main( ) { /* local/automatic variables that can only be used in this function and that are destroyed when the function ends */ int i, maxValue, nrValues; inputPositiveInt("Input max random value to generate: "); maxValue = inputValue; inputPositiveInt("Input number of random ints to generate: "); nrValues = inputValue; for (i = 0; i < nrValues; i++) getRandomInt( maxValue ); printf( “%d: %d\n", i + 1, randomInt ); } return 0;