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

Similar documents
Appendix A. The Preprocessor

Conditional Compilation

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

CSCI 171 Chapter Outlines

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

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

Unit 4 Preprocessor Directives

OBJECT ORIENTED PROGRAMMING USING C++

Chapter 7: Preprocessing Directives

COMsW Introduction to Computer Programming in C

Topic 6: A Quick Intro To C

fpp: Fortran preprocessor March 9, 2009

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

CSE 374 Programming Concepts & Tools

A Fast Review of C Essentials Part II

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

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

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

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

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

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

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


EL6483: Brief Overview of C Programming Language

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

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

Programming for Engineers C Preprocessor

CSE 374 Programming Concepts & Tools. Brandon Myers Winter 2015 C: Linked list, casts, the rest of the preprocessor (Thanks to Hal Perkins)

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

CSE341: Programming Languages Lecture 15 Macros. Zach Tatlock Winter 2018

What is a macro. CSE341: Programming Languages Lecture 15 Macros. Example uses. Using Racket Macros. Zach Tatlock Winter 2018

Modules:Context-Sensitive Keyword

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

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

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

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

COP4020 Programming Assignment 1 - Spring 2011

C Preprocessor. Prabhat Kumar Padhy

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

CS240: Programming in C

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


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

Flow Control. CSC215 Lecture

CSE 374 Programming Concepts & Tools

PP "C" Preprocessor User Guide

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

The Make Utility. Independent compilation. Large programs are difficult to maintain. Problem solved by breaking the program into separate files

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

The Make Utility. Independent compilation. Large programs are difficult to maintain. Problem solved by breaking the program into separate files

CSc 520 Principles of Programming Languages

Introduction to C CMSC 104 Spring 2014, Section 02, Lecture 6 Jason Tang

The C Preprocessor (and more)!

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

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

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

BLM2031 Structured Programming. Zeyneb KURT

4.2 Machine-Independent Macro Processor Features

PERIYAR CENTENARY POLYTECHNIC COLLEGE Periyar Nagar- Vallam Thanjavur

PROGRAMMAZIONE I A.A. 2017/2018

Computational Methods of Scientific Programming Fall 2007

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

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

MODULE 5: Pointers, Preprocessor Directives and Data Structures

G52CPP C++ Programming Lecture 6. Dr Jason Atkin

Errors During Compilation and Execution Background Information

AN OVERVIEW OF C. CSE 130: Introduction to Programming in C Stony Brook University

#include <stdio.h> int main() { printf ("hello class\n"); return 0; }

Modifiers. int foo(int x) { static int y=0; /* value of y is saved */ y = x + y + 7; /* across invocations of foo */ return y; }

Programming Language Basics

More on C programming

Code Structure Visualization

for (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; }

Page 1. Last Time. Today. Embedded Compilers. Compiler Requirements. What We Get. What We Want

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

Typescript on LLVM Language Reference Manual

CMPSC 311- Introduction to Systems Programming Module: Build Processing

Ruby: Introduction, Basics

Not Quite C Compiler version 1.0 b1

Columbus Schema for C/C++ Preprocessing

Intermediate Programming, Spring 2017*

1 Lexical Considerations

Programs. Function main. C Refresher. CSCI 4061 Introduction to Operating Systems

Language Translation. Compilation vs. interpretation. Compilation diagram. Step 1: compile. Step 2: run. compiler. Compiled program. program.

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

The New C Standard (Excerpted material)

Basic Types and Formatted I/O

Compiler, Assembler, and Linker

Appendix G C/C++ Notes. C/C++ Coding Style Guidelines Ray Mitchell 475

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

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Lectures 5-6: Introduction to C

How Compiling and Compilers Work

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

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

ELEC 377 C Programming Tutorial. ELEC Operating Systems

Lectures 5-6: Introduction to C

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

CMPSC 311- Introduction to Systems Programming Module: Build Processing

Chapter 4 Defining Classes I

Transcription:

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

Macro Definition Directive: #define #define <name> <body> Example: #define BUFF_SIZE 1000 A newline ends the macro body Macros can only be 1 line long Work-around: For longer bodies, use the line continuation character, \ Naming convention: SCREAMING_SNAKE_CASE Common use: compile-time constant int Buffer[BUFF_SIZE]; Also: #undef

GNU gcc Toolchain Run only macro preprocessor: -E $ gcc E test.c > test.i Standard file extension for preprocessed C (C++) is.i (.ii) More than just expanding macros: Begins by stripping comments Concatenates lines marked with \ May collapse white space Adds markers for filename and line numbers to help connect later errors to original location in source file

Text Substitution Gcc preprocessor doesn't really care that input is a C program Theoretically can be used on any text file Demo: ulisse.c, ulisse.ii Caveat: The preprocessor does rely on proper C conventions for tokenizing Apostrophes will mess things up In practice: preprocessing something other than C/C++ files with gcc is a hack, it is brittle, and it is probably a bad idea

Algorithmic Highlights Single pass Forward references are not expanded Nested invocation is permitted Expanded body is rescanned for more invocations Nested definitions are not permitted No recursion or mutual recursion Self references are not further expanded Circularity (mutual recursion) handled similarly: First cyclic reference is not expanded

Nesting Forward References Input foo = X; #define X 4 bar = X; Input #define SIZE BUFF #define BUFF 1024 Mem[SIZE]; Output foo = X; bar = 4; Output Mem[1024];

Still Single Pass Input #define BUFF 1024 #define SIZE BUFF #undef BUFF #define BUFF 2048 Mem[SIZE]; Output?

Macro Arguments Argument list follows name, without spaces #define <name>(<arglist>) <body> Example #define INC(X) X++ #define SUM(X,Y) X+Y Danger: Arithmetic grouping Macro is doing text substitution, not programming language call Scope issues may cause surprising problems

Problem: Unprotected Body Recall ternary operator ( _? _ : _ ) Consider #define MAX(X,Y) X > Y? X : Y Do these work? a = MAX(b,c); a = MAX(b,c) + 1; Result of expansion: a = b > c? b : c; a = b > c? b : c + 1; Solution: protect the body #define MAX(X,Y) (X > Y? X : Y)

Problem: Unprotected Args Consider another use of MAX macro flag = MAX(b<0,c<0); A disjunction of the two conditions? Result of expansion: flag = (b<0 > c<0? b<0 : c<0); Solution: protect the arguments #define MAX(X,Y) ((X) > (Y)?(X):(Y)) flag = ((b<0) > (c<0)?(b<0):(c<0));

Conditional Expansion Common condition is this macro (not) defined? #ifndef BUFF_SIZE #define BUFF_SIZE 1024 #endif /*BUFF_SIZE*/ Application: debugging modes #define DEBUG_ON... #ifdef DEBUG_ON printf (... ); #endif /*DEBUG_ON*/ Advantage: No space/time overhead Disadvantage: Change requires recompiling

File Inclusion Syntax #include "<filename>" Effect: Contents of <filename> inserted at that point #include f

Danger: Repeated Inclusion Multiple inclusion of the same file can lead to conflicts, eg double declaration File f1 includes lib1 and lib2 File lib1 includes lib2 Result: f1.i contains two copies of lib2 In the extreme: recursive inclusion File f1 includes f2 File f2 includes f1

Solution: Conditional Protect every file that will be included by other file(s) Convention Wrap entire file in #ifndef #endif Inside, define a unique macro (1/file) Example, file cat.h #ifndef CAT_H_PAGS #define CAT_H_PAGS... #endif /*CAT_H_PAGS*/

Predefined Macros Macros provided by the preprocessor Some are part of ANSI language standard FILE : current file name LINE : this line number in current file DATE / TIME : current date/time Some are compiler-specific (eg gcc) VERSION BASE_FILE INCLUDE_LEVEL Example use: Error or debug messages printf("error in %s, line %d\n", FILE, LINE );

Using Arguments in Strings ANSI C: Parameter substitution is not performed within quoted strings Example #define DISP(EXP) \ printf("exp = %d\n", EXP) DISP(i*j+1) Result of expansion: printf("exp = %d\n", i*j+1) Solution: "Stringizing" operator, # #define DISP(EXP) \ printf(#exp " = %d\n", EXP) Result of expansion: printf("i*j+1" " = %d\n", i*j+1)

Pitfall: Side effects Macros look like function calls Text substitution means semantics are not the same as function calls Example: Recall MAX macro #define MAX(X,Y) ((X) > (Y)?(X):(Y)) a = MAX(b++, c++) If b = 2, and c = 5 beforehand, what is the result? // a =, b =, c =

Pitfall: Swallow the Semicolon Macro consists of compound statement #define INC(X,Y) {X++; Y++} Tempting to use macro with semicolon INC(a, b); However, consider: if ( ) INC(a, b); else Result: compile-time error Solution: (notice missing semicolon) #define INC(X, Y) \ do { X++; Y++ } while(0)

Summary Macro definition with #define Single pass No forward references No nested definitions Nested invocations expanded (no cycles) Arguments are permitted Conditional expansion #ifdef File inclusion #include Coding idioms to prevent some mistakes Protect the body, protect the arguments Avoid arguments with side effects