Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Similar documents
Chapter 7: Preprocessing Directives

C for Engineers and Scientists: An Interpretive Approach. Chapter 7: Preprocessing Directives

OBJECT ORIENTED PROGRAMMING USING C++

Conditional Compilation

Programming for Engineers C Preprocessor

Have examined process Creating program Have developed program Written in C Source code

Unit 4 Preprocessor Directives

fpp: Fortran preprocessor March 9, 2009

A Fast Review of C Essentials Part II

Appendix A. The Preprocessor

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

C and C++ 2. Functions Preprocessor. Alan Mycroft

Problem Solving and 'C' Programming

3 PREPROCESSOR. Overview. Listing 3-0. Table 3-0.

Macros and Preprocessor. CGS 3460, Lecture 39 Apr 17, 2006 Hen-I Yang

Control flow and string example. C and C++ Functions. Function type-system nasties. 2. Functions Preprocessor. Alastair R. Beresford.

C Preprocessor. Prabhat Kumar Padhy

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Lecture 2: C Programming Basic

Macros in C/C++ Computer Science and Engineering College of Engineering The Ohio State University. Lecture 33

Errors During Compilation and Execution Background Information

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Contents Lecture 3. C Preprocessor, Chapter 11 Declarations, Chapter 8. Jonas Skeppstedt Lecture / 44

COMsW Introduction to Computer Programming in C

Topic 6: A Quick Intro To C

Practical C Issues:! Preprocessor Directives, Multi-file Development, Makefiles. CS449 Fall 2017

COSC 2P91. Bringing it all together... Week 4b. Brock University. Brock University (Week 4b) Bringing it all together... 1 / 22

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

The C Preprocessor (and more)!

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Intermediate Programming, Spring 2017*


PROGRAMMAZIONE I A.A. 2017/2018

CS240: Programming in C

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Slide Set 5. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Full file at C How to Program, 6/e Multiple Choice Test Bank

C Programming. The C Preprocessor and Some Advanced Topics. Learn More about #define. Define a macro name Create function-like macros.

Unit 1: Introduction to C Language. Saurabh Khatri Lecturer Department of Computer Technology VIT, Pune

The C Pre Processor ECE2893. Lecture 18. ECE2893 The C Pre Processor Spring / 10

Decision Making -Branching. Class Incharge: S. Sasirekha

Modules:Context-Sensitive Keyword

Language Reference Manual simplicity

MODULE 10 PREPROCESSOR DIRECTIVES

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

The C Preprocessor. Richard M. Stallman, Zachary Weinberg. For gcc version (GCC)

The New C Standard (Excerpted material)

ISO/IEC JTC1/SC22/WG5 N1247

CS3157: Advanced Programming. Outline

1 Lexical Considerations

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #54. Organizing Code in multiple files

CMPE-013/L. Expressions and Control

Tutorial No. 2 - Solution (Overview of C)

The C Preprocessor. Richard M. Stallman, Zachary Weinberg. For gcc version (pre-release) (GCC)

CSCI 171 Chapter Outlines

Computer Programming

C: Program Structure. Department of Computer Science College of Engineering Boise State University. September 11, /13

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

CSCI 2132 Software Development. Lecture 8: Introduction to C

Unit 7. Functions. Need of User Defined Functions

JTSK Programming in C II C-Lab II. Lecture 1 & 2

Pointers and Functions Passing Pointers to Functions CMPE-013/L. Pointers and Functions. Pointers and Functions Passing Pointers to Functions

ME 461 C review Session Fall 2009 S. Keres

CODE TIME TECHNOLOGIES. Abassi RTOS MISRA-C:2004. Compliance Report

Lesson 5: Functions and Libraries. EE3490E: Programming S1 2018/2019 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Model Viva Questions for Programming in C lab

Lecture 3. More About C

INDEX. Figure I-0. Listing I-0. Table I-0. Symbols.DIRECTIVE (see Assembler directives)? preprocessor operator 3-34

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

More on C programming

#include. Practical C Issues: #define. #define Macros. Example. #if

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

Compiler Theory. (GCC the GNU Compiler Collection) Sandro Spina 2009

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5

The C Preprocessor. for GCC version Richard M. Stallman Zachary Weinberg

Compiler, Assembler, and Linker

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

27-Sep CSCI 2132 Software Development Lecture 10: Formatted Input and Output. Faculty of Computer Science, Dalhousie University. Lecture 10 p.

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

Lexical Considerations

Jim Lambers ENERGY 211 / CME 211 Autumn Quarter Programming Project 4

Course Outline Introduction to C-Programming

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.

A Crash Course in C. Steven Reeves

Columbus Schema for C/C++ Preprocessing

Programming for Engineers Introduction to C

emacs customisation ($HOME/.emacs)

Oregon State University School of Electrical Engineering and Computer Science. CS 261 Recitation 2. Spring 2016

UNIT- 3 Introduction to C++

SOFTWARE ARCHITECTURE 5. COMPILER

CSE 374 Programming Concepts & Tools

Lectures 5-6: Introduction to C

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Lectures 5-6: Introduction to C

This exam is to be taken by yourself with closed books, closed notes, no calculators.

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Unit 3. Operators. School of Science and Technology INTRODUCTION

Transcription:

1

2

CMPE 013/L Pre Processor Commands Gabriel Hugh Elkaim Spring 2013 3

Introduction Preprocessing Affect program preprocessing and execution Capabilities Inclusion of additional C source files Definition of symbolic constants and macros Conditional preprocessing of a program Format of preprocessing directives A preprocessing directive consists of a sequence of preprocessing tokens that begins with a pound sign #, which must be the first non space character on the line. Some preprocessing directives are listed below. PreProcessor Directives Definition PreProcessor Directives arepartsofthecodethatgivespecial instructions to the compiler. They always begin with a # at the beginning of the line, and are used to direct the compiler with a number of specific commands. Conditional Compilation Symbolic Constants and Macros Source File Inclusion Macros Predefined Macros Line Control Error Directive 4

Direc tive #define #elif #else #endif #error #if #ifdef #ifndef #include #line #pragma # Null directive defined Desc ription Define a preprocessor macro. Alternatively include some text based on the value of another expression, if the previous #if, #ifdef, #ifndef, or #elif test failed. Alternatively include some text, if the previous #if, #ifdef, #ifndef, or #elif test failed. Terminate conditional text. Produce a compile time error with a designated message. Conditionally include text, based on the value of an expression. Conditionally include text, based on whether a macro name is defined. Conditionally include text, based on if a name is not a defined macro. Insert text from another source file. Give a line number for message. Compiler/interpreter specific features, not in C standard Preprocessing operator that yields 1 if a name is defined as a preprocessing macro and 0 otherwies; used in #if and #elif. Symbolic Constants and Macros The #define Preprocessing Directive This preprocessing directive is used to create symbolic constants and macros. Form #define identifier replacement-list defines an object like macro that causes each subsequent instance of the macro names to be replaced by the replacement list of preprocessing tokens that constitute the remainder of the directive. The new line is a character that terminates the #define preprocessing directive. 5

Symbolic Constants and Macros Symbolic constants The simple form of macro is particularly useful for introducing named constants into a program. It allows for easier modification of the constants later on.when programs are processed, all occurrences of symbolic constants indicated by identifier are replaced by the replacement list. Example: #define BLOCK_SIZE 0x100 we can write int size = BLOCK_SIZE; instead of int size = 0x100; in the program. Note: Cannot redefine symbolic constants with different values by multiple #define statements Symbolic Constants and Macros A preprocessing directive of the form #define identifier(identifier-list-opt) replacement-list new-line defines a function like macro with arguments, similar syntactically to a function call. The parameters are specified by the optional list of identifiers. Example: if a macro mul with two arguments is defined by #define mul(x,y) ((x)*(y)) then the source program line result = mul(5, a+b); is replaced with result = ((5)*(a+b)); 6

NOTE: Parentheses are important in macro definitions. Example: If macro mul is defined as #define mul(x,y) (x*y) The statement result = mul(5, a+b); in the source program becomes result = (5*a+b); The evaluation will be incorrect. #undef Undefine a symbolic constant or macro, which can later be redefined. Example: #define mul(x,y) ((x)*(y)) /* */ #undef mul int mul; /* mul can be used after it is undefined */ 7

The #include Preprocessing Directive Source File Inclusion Copy of a specified header file included in place of the directive. It has following two common forms. 1)#include <header.h> Searches standard library for header file and replaces the directive by the entire contents of the file. In Ch, the header is searched according to the paths specified by the the system variable _ipath. C compilers in Unix will typically search the header file in the directory /usr/include. In Visual C++, the header file is searched based on the paths in the environment variable INCLUDE. or cl I C:/home/assount/include program.c Used for standard library files 2) #include header.h" C compilers and interpreters will first search the header file in the same directory where the file is being processed, which typically is the current directory. Then search the header file in the paths as if it was included by #include <header.h>. Applications Loading header files #include <stdio.h> Programs with multiple source files to be compiled together Includes user defined header files which have common declarations and definitions (classes, structures, function prototypes, and macros) 8

Conditional Compilation Conditional compilation Enables the user to control the compilation of the program, screen out portions of source code that are not to be compiled. Structure The structure is similar to if and else statement in C. Conditional preprocessing directives #if, #else, #elif, and #endif Preprocessing directives of the forms #if expr1 /*... */ #elif expr2 /*... */ #else /*... */ #endif check whether the controlling expression evaluates to nonzero. Every #if ends with #endif Example: #if defined(_hpux_) printf( I am using HP-UX\n ); #elif defined(_win32_) printf( I am using Windows\n); #endif 9

Preprocessing directives of the forms # ifdef identifier # ifndef identifier check whether the identifier is or is not currently defined as a macro name. #ifdef identifier is the short form of #if defined(identifier) #ifndef identifier is the short form of #if!defined(identifier) Each directive s condition is checked in order. If it evaluates to false (zero), then the group that it controls is skipped: directives are processed only through the name that determines the directive in order to keep track of the level of nested conditionals. Only the first group whose control condition evaluates to true (nonzero) is processed. If none of the conditions evaluates to true, and there is a #else directive, then the group controlled by the #else is processed; if lacking a #else directive, then all the groups until the #endif are skipped. Comment out a segment of code Comment out code segment which contains /*... */ Use following format to comment out the segment of code double d = some_func(); #ifdef JUNK /* This code segment will be commented out */ printf( d = %f\n, d); #endif The code segment will be commented out when JUNK is not defined, To uncomment the code segment, define JUNK or remove #ifdef JUNK and #endif. 10

To include a header file in a program only once, it is typically handled using the combination of the following preprocessing directives #ifndef, #define, and #endif. For example, a header file header.h may consist of the following code fragment. #ifndef HEADER_H #define HEADER_H /* code */ #endif Example: /* File: accelhead.c */ #include <stdio.h> /* local header file */ #include "accel.h" int main() { /* declare variables */ double a, mu, m, t; /* File: accel.h */ #ifndef ACCEL_H #define ACCEL_H #define M_G 9.81 double force(double t); double accel(double t, double mu, double m); #endif } /* Initialize variables */ mu = 0.2; m = 5.0; t = 2.0; /* processing */ a = accel(t, mu, m); /* display the output and termination */ printf("acceleration a = %f (m/s^2)\n", a); return 0; double force(double t) { double p; } p = 4*(sin(t)-3)+20; return p; double accel(double t, double mu, double m) { double a, p; } p = force(t); a = (p-mu*m*m_g)/m; return a; 11

Macros defined in C Predefined Macros Macro Name LINE FILE DATE TIME STDC Description The line number of the current source program line which is expressed as a decimal integral constant The name of the current source file which is expressed as a string constant. The calendar date of the translation which is expressed as a string constant form Mmm dd yyy. Mmm is produced by asctime(). The current time which is expressed as a string constant of the form hh:mm:ss, as returned by asctime(). The decimal constant 1 for C comforming impelementtation. STDC_VERSION The decimal constant 199901L for C99 comforming implementation Example: /* filename: predefined.c */ #include <stdio.h> int main() { printf(" FILE = %s\n", FILE ); printf(" LINE = %d\n", LINE ); printf(" DATE = %s\n", DATE ); printf(" TIME = %s\n", TIME ); #ifdef STDC printf(" STDC = %d\n", STDC ); #endif #ifdef STDC_VERSION printf(" STDC_VERSION = %d\n", STDC_VERSION ); #endif return 0; } 12

Output: FILE = predefined.c LINE = 6 DATE = Feb 24 2003 TIME = 00:09:42 STDC = 1 STDC_VERSION_ = 199901 /* File: printerror.c */ #include <stdio.h> #define printerror() printf("error in %s:%s():%d\n", \ FILE, func, LINE ); void funcname1() { printerror(); } void funcname2() { printerror(); } int main() { funcname1(); funcname2(); return 0; } Example Output Error in printerror.c:funcname1():7 Error in printerror.c:funcname2():10 13

NULL Directive A preprocessing directive of the form #new-line has no effect on the program. The line is ignored. Debugging code #define DEBUG /*... */ double x; x = some_func(); #ifdef DEBUG printf( The value of x = %f\n, x); #endif Defining DEBUG to print out the value of x. After debugging, remove #define statement. The debugging statements are ignored. 14

Line Control The #line directive can be used to alter the line numbers assigned to the source code. This directive gives a new line number to the following line, which is then incremented to derive the line number for subsequent lines. A preprocessing directive of the form #line digit-sequence new-line causes the implementation to behave as if the following sequence of source lines begins with a source line that has a line number as specified by the digit sequence. A preprocessing directive of the form #line digit-sequence s-char-sequence-opt new-line sets the presumed line number similarly and changes the presumed name of the source file to be the contents of the character string literal. The name of the source file is stored in the predefined macro FILE internally. Example: /* FILENAME: linefile.c */ #include <stdio.h> int main() { printf( before line directive, line number is %d \n, LINE ); printf( the FILE predefined macro = %s\n, FILE ); #line 200 newname printf( after line directive, line number is %d \n, LINE ); printf( The FILE predefined macro = %s\n, FILE ); return 0; } Output: before line directive, line number is 4 the FILE predefined macro = linefile.c after line directive, line number is 200 the FILE predefined macro = newname 15

Definition Macros: PreProcessor Directives Macros are text replacements created with #define that insert code into your program. Macros may take parameters like a function, but the macro code and parameters are always inserted into code by text substitution. #define text(args) Can be used instead of functions in certain instances Made to look like C functions Definition Macros Macros with #define Macros are text replacements created with #define that insert code into your program. Macros may take parameters like a function, but the macro code and parameters are always inserted into code by text substitution. Are evaluated by the preprocessor Are not executable code themselves Can control the generation of code before the compilation process Provide shortcuts 16

Macros with #define Simple Macros Text substitution as seen earlier Syntax #define label text Every instance of label in the current file will be replaced by text text can be anything you can type into your editor Arithmetic expressions evaluated at compile time Example #define Fosc 4000000 #define Tcy (0.25 * (1/Fosc)) #define Setup InitSystem(Fosc, 250, 0x5A) Macros with #define Argument Macros Create a function like macro Syntax #define label(arg 1,,arg n ) code The code must fit on a single line or use '\' to split lines Text substitution used to insert arguments into code Each instance of label() will be expanded into code This is not the same as a C function! Example #define min(x, y) ((x)<(y)?(x):(y)) #define square(x) ((x)*(x)) #define swap(x, y) { x ^= y; y ^= x; x ^= y; } 17

Example Macros with #define Argument Macros Side Effects #define square(a) ((a)*(a)) Extreme care must be exercised when using macros. Consider the following use of the above macro: i = 5; x = square(i++); Results: Wrong Answers! x = 30 x = square(i++); i= 7 expands to: x = ((i++)*(i++)); So igets incremented twice, not once at the end as expected. The # token appearing within a macro definition is recognized as a unary stringization operator. In a replacement list, if a parameter is immediately preceded by a # preprocessing token, both are replaced by a single character string literal preprocessing token that contains the spelling of the preprocessing token sequence for the corresponding argument. Example: Converting Token to Strings > #define TEST(a) #a > printf( %s, TEST(abcd)) abcd The macro parameter abcd has been converted to the string constant abcd. It is equivalent to > printf( %s, abcd ) 18

Each occurrence of white space between the argument s preprocessing tokens becomes a single space character in the character string literal. White space before the first preprocessing token and after the last preprocessing token composing the argument is deleted. Example: > #define TEST(a) #a > printf( 1%s2, TEST( a b )) 1a b2 The argument is turned into the string constant a b. Token Merging in Macro Expansions The merging of tokens to form new tokens in C is controlled by the presence of the merging operator ## in macro definitions. The common use of concatenation is concatenating two names into a longer name. It is possible to concatenate two numbers, or a number and a name, such as 1.5 and e3, into a number. Example: > #define CONC2(a, b) a ## b > #define CONC3(a, b, c) a ## b ## c > CONC2(1, 2) 12 // numbers 1 and 2 concatenated to 12 > CONC3(3, +, 4) 7 // 3, +, and 4 becomes 3+4, which equals 7 > printf( CONC2(1,2) = %d, CONC2(1,2)) CONC2(1,2) = 12 19

A preprocessing directive of the form #error pp-tokens-opt new-line causes the implementation to produce a diagnostic message that includes the specified sequence of preprocessing tokens and the interpretation to cease. Example: Error Directive /* FILENAME: error.c */ #include <stdio.h> #define MACRO int main() { #ifdef MACRO #error This is an error, if your code reach here /* the code here will not be processed */ #else printf("ok \n"); #endif return 0; } Output: ERROR: #error: This is an error, if your code reach here ERROR: syntax error before or at line 6 in file error.c' ==>: #error This is an error, if your code reach here BUG: #error This is an error, if your code reach here<==??? WARNING: cannot execute command error.c 20

Lab Exercise 19 Macros with #define Exercise 19 #define Macros Open the project s workspace: On the class website /Examples/Lab19.zip > Load Lab19.mcw 1 Open MPLAB and select Open Workspace from the File menu. Open the file listed above. If you already have a project open in MPLAB, close it by selecting Close Workspace from the File menu before opening a new one. 21

Exercise 19 #define Macros Compile and run the code: 2 Compile (Build All) 3 Run 4 Halt 2 Click on the Build All button. 3 If no errors are reported, click on the Run button. 4 Click on the Halt button. Exercise 19 #define Macros #define Macro Definition and Use /*---------------------------------------------------------------------------- MACROS ----------------------------------------------------------------------------*/ #define square(m) ((m) * (m)) #define BaudRate(DesiredBR, FoscMHz) ((((FoscMHz * 1000000)/DesiredBR)/64)-1) /*============================================================================ FUNCTION: main() ============================================================================*/ int main(void) { x = square(3); printf("x = %d\n", x); } SPBRG = BaudRate(9600, 16); printf("spbrg = %d\n", SPBRG); 22

Exercise 19 Conclusions #define macros can dramatically simplify your code and make it easier to maintain Extreme care must be taking when crafting a macro due to the way they are substituted within the text of your code Questions? 23