Module 05 Preprocessor and Macros in C

Tushar B Kute
Tushar B KuteResearcher at http://mitu.co.in
See through C
Module 5
Macros and preprocessors
Tushar B Kute
http://tusharkute.com
The C preprocessor and its role
2
cpp
(C preprocessor)
cc1
(C compiler)
source
program
compiled
code
C compiler (e.g., gcc)
expanded
code
• expand some kinds of characters
• discard whitespace and comments
– each comment is replaced with a single space
• process directives:
– file inclusion (#include)
– macro expansion (#define)
– conditional compilation (#if, #ifdef, …)
#include
• Specifies that the preprocessor should read in the contents of the specified file
– usually used to read in type definitions, prototypes, etc.
– proceeds recursively
• #includes in the included file are read in as well
• Two forms:
– #include <filename>
• searches for filename from a predefined list of directories
• the list can be extended via “gcc –I dir”
– #include “filename”
• looks for filename specified as a relative or absolute path
3
#include : Example
4
a predefined include file that:
• comes with the system
• gives type declarations,
prototypes for library routines
(printf)
where does it come from?
– man 3 printf :
#include: cont’d
• We can also define our own header files:
– a header file has file-extension ‘.h’
– these header files typically contain “public” information
• type declarations
• macros and other definitions
• function prototypes
– often, the public information associated with a code file
foo.c will be placed in a header file foo.h
– these header files are included by files that need that
public information
#include “myheaderfile.h”
5
Macros
• A macro is a symbol that is recognized by the preprocessor and
replaced by the macro body
– Structure of simple macros:
#define identifier replacement_list
– Examples:
#define BUFFERSZ 1024
#define WORDLEN 64
6
Using simple macros
• We just use the macro name in place of the value, e.g.:
#define BUFLEN 1024
#define Pi 3.1416
…
char buffer[BUFLEN];
…
area = Pi * r * r;
7
NOT:
#define BUFLEN = 1024
#define Pi 3.1416;

Example 1
8
Example 2
9
we can “macroize”
symbols selectively
Parameterized macros
• Macros can have parameters
– these resemble functions in some ways:
• macro definition ~ formal parameters
• macro use ~ actual arguments
– Form:
#define macroName(arg1, …, argn) replacement_list
– Example:
#define deref(ptr) *ptr
#define MAX(x,y) x > y ? x : y
10
no space here!
(else preprocessor will
assume we’re defining
a simple macro
Example
11
Macros vs. functions
• Macros may be (slightly) faster
– don’t incur the overhead of function call/return
– however, the resulting code size is usually larger
• this can lead to loss of speed
• Macros are “generic”
– parameters don’t have any associated type
– arguments are not type-checked
• Macros may evaluate their arguments more than once
– a function argument is only evaluated once per call
12
Macros vs. Functions: Argument Evaluation
• Macros and functions may behave differently if an argument is referenced multiple times:
– a function argument is evaluated once, before the call
– a macro argument is evaluated each time it is encountered
in the macro body.
• Example:
13
int dbl(x) { return x + x;}
…
u = 10; v = dbl(u++);
printf(“u = %d, v = %d”, u, v);
prints: u = 11, v = 20
#define Dbl(x) x + x
…
u = 10; v = Dbl(u++);
printf(“u = %d, v = %d”, u, v);
prints: u = 12, v = 21
Dbl(u++)
expands to:
u++ + u++
Properties of macros
• Macros may be nested
– in definitions, e.g.:
#define Pi 3.1416
#define Twice_Pi 2*Pi
– in uses, e.g.:
#define double(x) x+x
#define Pi 3.1416
…
if ( x > double(Pi) ) …
• Nested macros are expanded recursively
14
Header Files
• Have a file extension “.h”
• Contain shared definitions
– typedefs
– macros
– function prototypes
• referenced via “#include” directives
15
Header files: example
16
typedefs
• Allow us to define aliases for types
• Syntax:
typedef old_type_name new_type_name;
• new_type_name becomes an alias for old_type_name
• Example:
– typedef int BasePay;
– typedef struct node {
int value;
struct node *next;
} node;
17
Example
18
defines “wcnode” as an
alias for “struct wc”
we can use “wcnode” in
place of“struct wc”
but not here, since
“wcnode” has not yet
been defined
What if a file is #included multiple times?
19
foo.h
bar1.h bar2.h
bar.c
Conditional Compilation: #ifdef
#ifdef identifier
line1
…
linen
#endif
• macros can be defined by the compiler:
– gcc –D macroName
– gcc –D macroName=definition
• macros can be defined without giving them a specific
value, e.g.:
– #define macroName
20
line1 … linen will be included if
identifier has been defined as a
macro; otherwise nothing will
happen.
Conditional Compilation: #ifndef
#ifndef identifier
line1
…
linen
#endif
21
line1 … linen will be
included if identifier
is NOT defined as a
macro; otherwise
nothing will happen.
Solution to multiple inclusion problem
The header file is written as follows:
#ifndef file_specific_flag
#define file_specific_flag
…contents of file…
#endif
• file_specific_flag usually constructed from the name of the header file:
E.g.: file = foo.h ⇒ flag = _FOO_H_
– try to avoid macro names starting with ‘_’
22
indicates whether or
not this file has been
included already
Another use of #ifdefs
• They can be useful for controlling debugging output
– Example 1: guard debugging code with #ifdefs:
#ifdef DEBUG
…debug message…
#endif
– Example 2: use the debug macro to control what
debugging code appears in the program:
#ifdef DEBUG
#define DMSG(msg) printf(msg) // debugging output
#else
#define DMSG(msg) {} // empty statement
#endif
23
straightforward, but needs
discipline to use consistently
Generalizing #ifdef
#if constant-expression
line1
…
linen
#endif
⇒ line1 … linen included if constant-expression evaluates to a non-zero value
24
Common uses:
• #if 1
or
• #if 0
__LINE__ current line number of the source file
__FILE__ name of the current source file
__TIME__ time of translation
__STDC__ 1 if the compiler conforms to ANSI C
printf("working on %sn", __FILE__);
Predefined Macros
Adapted originally from:
CSc 352
An Introduction to the C Preprocessor
Saumya Debray
Dept. of Computer Science
The University of Arizona, Tucson
debray@cs.arizona.edu
Thank you
This presentation is created using LibreOffice Impress 3.6.2.2
1 of 26

Recommended

Preprocessor directives in c language by
Preprocessor directives in c languagePreprocessor directives in c language
Preprocessor directives in c languagetanmaymodi4
7K views30 slides
Preprocessor by
PreprocessorPreprocessor
PreprocessorLearn By Watch
9.4K views24 slides
Pointers in c++ by
Pointers in c++Pointers in c++
Pointers in c++Rajat Busheheri
3.5K views22 slides
Control statements in c by
Control statements in cControl statements in c
Control statements in cSathish Narayanan
16.8K views39 slides
Storage class in C Language by
Storage class in C LanguageStorage class in C Language
Storage class in C LanguageNitesh Kumar Pandey
27K views15 slides
File handling in c by
File handling in cFile handling in c
File handling in cDavid Livingston J
28.6K views34 slides

More Related Content

What's hot

RECURSION IN C by
RECURSION IN C RECURSION IN C
RECURSION IN C v_jk
14.2K views35 slides
user defined function by
user defined functionuser defined function
user defined functionKing Kavin Patel
8.3K views21 slides
Preprocessor in C by
Preprocessor in CPreprocessor in C
Preprocessor in CPrabhu Govind
2.9K views7 slides
Structure of a C program by
Structure of a C programStructure of a C program
Structure of a C programDavid Livingston J
22.5K views16 slides
Decision making statements in C programming by
Decision making statements in C programmingDecision making statements in C programming
Decision making statements in C programmingRabin BK
5.6K views21 slides
Conditional Statement in C Language by
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C LanguageShaina Arora
12.1K views22 slides

What's hot(20)

RECURSION IN C by v_jk
RECURSION IN C RECURSION IN C
RECURSION IN C
v_jk14.2K views
Decision making statements in C programming by Rabin BK
Decision making statements in C programmingDecision making statements in C programming
Decision making statements in C programming
Rabin BK5.6K views
Conditional Statement in C Language by Shaina Arora
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
Shaina Arora12.1K views
structure and union by student
structure and unionstructure and union
structure and union
student15.4K views
Variables, Data Types, Operator & Expression in c in detail by gourav kottawar
Variables, Data Types, Operator & Expression in c in detailVariables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detail
gourav kottawar5.8K views
Basics of c++ Programming Language by Ahmad Idrees
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees47.9K views

Viewers also liked

Macro by
MacroMacro
MacroGoogle
24.4K views31 slides
System Programming Unit II by
System Programming Unit IISystem Programming Unit II
System Programming Unit IIManoj Patil
99.7K views65 slides
The C Preprocessor by
The C PreprocessorThe C Preprocessor
The C Preprocessoriuui
3K views78 slides
Embedded C workshop by
Embedded C workshopEmbedded C workshop
Embedded C workshopMostafa El-koumy
937 views25 slides
Embedded C - Lecture 2 by
Embedded C - Lecture 2Embedded C - Lecture 2
Embedded C - Lecture 2Mohamed Abdallah
4.1K views95 slides

Viewers also liked(13)

Macro by Google
MacroMacro
Macro
Google24.4K views
System Programming Unit II by Manoj Patil
System Programming Unit IISystem Programming Unit II
System Programming Unit II
Manoj Patil99.7K views
The C Preprocessor by iuui
The C PreprocessorThe C Preprocessor
The C Preprocessor
iuui3K views
8051 programming skills using EMBEDDED C by Aman Sharma
8051 programming skills using EMBEDDED C8051 programming skills using EMBEDDED C
8051 programming skills using EMBEDDED C
Aman Sharma13.4K views
Question paper with solution the 8051 microcontroller based embedded systems... by manishpatel_79
Question paper with solution  the 8051 microcontroller based embedded systems...Question paper with solution  the 8051 microcontroller based embedded systems...
Question paper with solution the 8051 microcontroller based embedded systems...
manishpatel_79119.9K views
Embedded C programming based on 8051 microcontroller by Gaurav Verma
Embedded C programming based on 8051 microcontrollerEmbedded C programming based on 8051 microcontroller
Embedded C programming based on 8051 microcontroller
Gaurav Verma105.5K views
Writing c code for the 8051 by Quản Minh Tú
Writing c code for the 8051Writing c code for the 8051
Writing c code for the 8051
Quản Minh Tú21.6K views
LinkedIn SlideShare: Knowledge, Well-Presented by SlideShare
LinkedIn SlideShare: Knowledge, Well-PresentedLinkedIn SlideShare: Knowledge, Well-Presented
LinkedIn SlideShare: Knowledge, Well-Presented
SlideShare579.8K views

Similar to Module 05 Preprocessor and Macros in C

1614745770521_vivek macros.pptx by
1614745770521_vivek macros.pptx1614745770521_vivek macros.pptx
1614745770521_vivek macros.pptxVivekSaini87
3 views18 slides
Preprocessor by
PreprocessorPreprocessor
Preprocessorlalithambiga kamaraj
1K views32 slides
6 preprocessor macro header by
6 preprocessor macro header6 preprocessor macro header
6 preprocessor macro headerhasan Mohammad
108 views9 slides
Unit 5 quesn b ans5 by
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5Sowri Rajan
14 views23 slides
Preprocessor directives in c laguage by
Preprocessor directives in c laguagePreprocessor directives in c laguage
Preprocessor directives in c laguageTanmay Modi
1.2K views30 slides
Unit 5 quesn b ans5 by
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5Sowri Rajan
9 views23 slides

Similar to Module 05 Preprocessor and Macros in C(20)

1614745770521_vivek macros.pptx by VivekSaini87
1614745770521_vivek macros.pptx1614745770521_vivek macros.pptx
1614745770521_vivek macros.pptx
VivekSaini873 views
Unit 5 quesn b ans5 by Sowri Rajan
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
Sowri Rajan14 views
Preprocessor directives in c laguage by Tanmay Modi
Preprocessor directives in c laguagePreprocessor directives in c laguage
Preprocessor directives in c laguage
Tanmay Modi1.2K views
嵌入式Linux課程-GNU Toolchain by 艾鍗科技
嵌入式Linux課程-GNU Toolchain嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain
艾鍗科技2.4K views
3 1. preprocessor, math, stdlib by 웅식 전
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib
웅식 전1.1K views
Csdfsadf by Atul Setu
CsdfsadfCsdfsadf
Csdfsadf
Atul Setu378 views
Preprocessor by Võ Hòa
PreprocessorPreprocessor
Preprocessor
Võ Hòa656 views
What is wrong with the following macro of a MAX function #define MAX.docx by ajoy21
 What is wrong with the following macro of a MAX function #define MAX.docx What is wrong with the following macro of a MAX function #define MAX.docx
What is wrong with the following macro of a MAX function #define MAX.docx
ajoy213 views

More from Tushar B Kute

Apache Pig: A big data processor by
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processorTushar B Kute
3.2K views50 slides
01 Introduction to Android by
01 Introduction to Android01 Introduction to Android
01 Introduction to AndroidTushar B Kute
869 views15 slides
Ubuntu OS and it's Flavours by
Ubuntu OS and it's FlavoursUbuntu OS and it's Flavours
Ubuntu OS and it's FlavoursTushar B Kute
1.7K views34 slides
Install Drupal in Ubuntu by Tushar B. Kute by
Install Drupal in Ubuntu by Tushar B. KuteInstall Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. KuteTushar B Kute
893 views25 slides
Install Wordpress in Ubuntu Linux by Tushar B. Kute by
Install Wordpress in Ubuntu Linux by Tushar B. KuteInstall Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteTushar B Kute
739 views26 slides
Share File easily between computers using sftp by
Share File easily between computers using sftpShare File easily between computers using sftp
Share File easily between computers using sftpTushar B Kute
2.2K views29 slides

More from Tushar B Kute(20)

Apache Pig: A big data processor by Tushar B Kute
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processor
Tushar B Kute3.2K views
01 Introduction to Android by Tushar B Kute
01 Introduction to Android01 Introduction to Android
01 Introduction to Android
Tushar B Kute869 views
Ubuntu OS and it's Flavours by Tushar B Kute
Ubuntu OS and it's FlavoursUbuntu OS and it's Flavours
Ubuntu OS and it's Flavours
Tushar B Kute1.7K views
Install Drupal in Ubuntu by Tushar B. Kute by Tushar B Kute
Install Drupal in Ubuntu by Tushar B. KuteInstall Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. Kute
Tushar B Kute893 views
Install Wordpress in Ubuntu Linux by Tushar B. Kute by Tushar B Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteInstall Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. Kute
Tushar B Kute739 views
Share File easily between computers using sftp by Tushar B Kute
Share File easily between computers using sftpShare File easily between computers using sftp
Share File easily between computers using sftp
Tushar B Kute2.2K views
Signal Handling in Linux by Tushar B Kute
Signal Handling in LinuxSignal Handling in Linux
Signal Handling in Linux
Tushar B Kute10.4K views
Implementation of FIFO in Linux by Tushar B Kute
Implementation of FIFO in LinuxImplementation of FIFO in Linux
Implementation of FIFO in Linux
Tushar B Kute3.3K views
Implementation of Pipe in Linux by Tushar B Kute
Implementation of Pipe in LinuxImplementation of Pipe in Linux
Implementation of Pipe in Linux
Tushar B Kute5.2K views
Basic Multithreading using Posix Threads by Tushar B Kute
Basic Multithreading using Posix ThreadsBasic Multithreading using Posix Threads
Basic Multithreading using Posix Threads
Tushar B Kute1.5K views
Part 04 Creating a System Call in Linux by Tushar B Kute
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in Linux
Tushar B Kute3.8K views
Part 03 File System Implementation in Linux by Tushar B Kute
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in Linux
Tushar B Kute3.4K views
Part 02 Linux Kernel Module Programming by Tushar B Kute
Part 02 Linux Kernel Module ProgrammingPart 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module Programming
Tushar B Kute3.6K views
Part 01 Linux Kernel Compilation (Ubuntu) by Tushar B Kute
Part 01 Linux Kernel Compilation (Ubuntu)Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)
Tushar B Kute3.7K views
Open source applications softwares by Tushar B Kute
Open source applications softwaresOpen source applications softwares
Open source applications softwares
Tushar B Kute1K views
Introduction to Ubuntu Edge Operating System (Ubuntu Touch) by Tushar B Kute
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Tushar B Kute5.6K views
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteUnit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Tushar B Kute3.9K views
Technical blog by Engineering Students of Sandip Foundation, itsitrc by Tushar B Kute
Technical blog by Engineering Students of Sandip Foundation, itsitrcTechnical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrc
Tushar B Kute870 views
Chapter 01 Introduction to Java by Tushar B Kute by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute3K views
Chapter 02: Classes Objects and Methods Java by Tushar B Kute by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute8.4K views

Recently uploaded

Top-5-production-devconMunich-2023-v2.pptx by
Top-5-production-devconMunich-2023-v2.pptxTop-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptxTier1 app
9 views42 slides
Introduction to Maven by
Introduction to MavenIntroduction to Maven
Introduction to MavenJohn Valentino
7 views10 slides
What is API by
What is APIWhat is API
What is APIartembondar5
16 views15 slides
JioEngage_Presentation.pptx by
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptxadmin125455
9 views4 slides
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile... by
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...Stefan Wolpers
49 views38 slides
Google Solutions Challenge 2024 Talk pdf by
Google Solutions Challenge 2024 Talk pdfGoogle Solutions Challenge 2024 Talk pdf
Google Solutions Challenge 2024 Talk pdfMohdAbdulAleem4
47 views17 slides

Recently uploaded(20)

Top-5-production-devconMunich-2023-v2.pptx by Tier1 app
Top-5-production-devconMunich-2023-v2.pptxTop-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptx
Tier1 app9 views
JioEngage_Presentation.pptx by admin125455
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptx
admin1254559 views
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile... by Stefan Wolpers
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
Stefan Wolpers49 views
Google Solutions Challenge 2024 Talk pdf by MohdAbdulAleem4
Google Solutions Challenge 2024 Talk pdfGoogle Solutions Challenge 2024 Talk pdf
Google Solutions Challenge 2024 Talk pdf
MohdAbdulAleem447 views
Introduction to Git Source Control by John Valentino
Introduction to Git Source ControlIntroduction to Git Source Control
Introduction to Git Source Control
John Valentino9 views
Mobile App Development Company by Richestsoft
Mobile App Development CompanyMobile App Development Company
Mobile App Development Company
Richestsoft 6 views
Electronic AWB - Electronic Air Waybill by Freightoscope
Electronic AWB - Electronic Air Waybill Electronic AWB - Electronic Air Waybill
Electronic AWB - Electronic Air Waybill
Freightoscope 7 views
Understanding HTML terminology by artembondar5
Understanding HTML terminologyUnderstanding HTML terminology
Understanding HTML terminology
artembondar59 views
Supercharging your Python Development Environment with VS Code and Dev Contai... by Dawn Wages
Supercharging your Python Development Environment with VS Code and Dev Contai...Supercharging your Python Development Environment with VS Code and Dev Contai...
Supercharging your Python Development Environment with VS Code and Dev Contai...
Dawn Wages9 views
Top-5-production-devconMunich-2023.pptx by Tier1 app
Top-5-production-devconMunich-2023.pptxTop-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptx
Tier1 app10 views
aATP - New Correlation Confirmation Feature.pptx by EsatEsenek1
aATP - New Correlation Confirmation Feature.pptxaATP - New Correlation Confirmation Feature.pptx
aATP - New Correlation Confirmation Feature.pptx
EsatEsenek1225 views
How to build dyanmic dashboards and ensure they always work by Wiiisdom
How to build dyanmic dashboards and ensure they always workHow to build dyanmic dashboards and ensure they always work
How to build dyanmic dashboards and ensure they always work
Wiiisdom18 views
Automated Testing of Microsoft Power BI Reports by RTTS
Automated Testing of Microsoft Power BI ReportsAutomated Testing of Microsoft Power BI Reports
Automated Testing of Microsoft Power BI Reports
RTTS13 views

Module 05 Preprocessor and Macros in C

  • 1. See through C Module 5 Macros and preprocessors Tushar B Kute http://tusharkute.com
  • 2. The C preprocessor and its role 2 cpp (C preprocessor) cc1 (C compiler) source program compiled code C compiler (e.g., gcc) expanded code • expand some kinds of characters • discard whitespace and comments – each comment is replaced with a single space • process directives: – file inclusion (#include) – macro expansion (#define) – conditional compilation (#if, #ifdef, …)
  • 3. #include • Specifies that the preprocessor should read in the contents of the specified file – usually used to read in type definitions, prototypes, etc. – proceeds recursively • #includes in the included file are read in as well • Two forms: – #include <filename> • searches for filename from a predefined list of directories • the list can be extended via “gcc –I dir” – #include “filename” • looks for filename specified as a relative or absolute path 3
  • 4. #include : Example 4 a predefined include file that: • comes with the system • gives type declarations, prototypes for library routines (printf) where does it come from? – man 3 printf :
  • 5. #include: cont’d • We can also define our own header files: – a header file has file-extension ‘.h’ – these header files typically contain “public” information • type declarations • macros and other definitions • function prototypes – often, the public information associated with a code file foo.c will be placed in a header file foo.h – these header files are included by files that need that public information #include “myheaderfile.h” 5
  • 6. Macros • A macro is a symbol that is recognized by the preprocessor and replaced by the macro body – Structure of simple macros: #define identifier replacement_list – Examples: #define BUFFERSZ 1024 #define WORDLEN 64 6
  • 7. Using simple macros • We just use the macro name in place of the value, e.g.: #define BUFLEN 1024 #define Pi 3.1416 … char buffer[BUFLEN]; … area = Pi * r * r; 7 NOT: #define BUFLEN = 1024 #define Pi 3.1416; 
  • 9. Example 2 9 we can “macroize” symbols selectively
  • 10. Parameterized macros • Macros can have parameters – these resemble functions in some ways: • macro definition ~ formal parameters • macro use ~ actual arguments – Form: #define macroName(arg1, …, argn) replacement_list – Example: #define deref(ptr) *ptr #define MAX(x,y) x > y ? x : y 10 no space here! (else preprocessor will assume we’re defining a simple macro
  • 12. Macros vs. functions • Macros may be (slightly) faster – don’t incur the overhead of function call/return – however, the resulting code size is usually larger • this can lead to loss of speed • Macros are “generic” – parameters don’t have any associated type – arguments are not type-checked • Macros may evaluate their arguments more than once – a function argument is only evaluated once per call 12
  • 13. Macros vs. Functions: Argument Evaluation • Macros and functions may behave differently if an argument is referenced multiple times: – a function argument is evaluated once, before the call – a macro argument is evaluated each time it is encountered in the macro body. • Example: 13 int dbl(x) { return x + x;} … u = 10; v = dbl(u++); printf(“u = %d, v = %d”, u, v); prints: u = 11, v = 20 #define Dbl(x) x + x … u = 10; v = Dbl(u++); printf(“u = %d, v = %d”, u, v); prints: u = 12, v = 21 Dbl(u++) expands to: u++ + u++
  • 14. Properties of macros • Macros may be nested – in definitions, e.g.: #define Pi 3.1416 #define Twice_Pi 2*Pi – in uses, e.g.: #define double(x) x+x #define Pi 3.1416 … if ( x > double(Pi) ) … • Nested macros are expanded recursively 14
  • 15. Header Files • Have a file extension “.h” • Contain shared definitions – typedefs – macros – function prototypes • referenced via “#include” directives 15
  • 17. typedefs • Allow us to define aliases for types • Syntax: typedef old_type_name new_type_name; • new_type_name becomes an alias for old_type_name • Example: – typedef int BasePay; – typedef struct node { int value; struct node *next; } node; 17
  • 18. Example 18 defines “wcnode” as an alias for “struct wc” we can use “wcnode” in place of“struct wc” but not here, since “wcnode” has not yet been defined
  • 19. What if a file is #included multiple times? 19 foo.h bar1.h bar2.h bar.c
  • 20. Conditional Compilation: #ifdef #ifdef identifier line1 … linen #endif • macros can be defined by the compiler: – gcc –D macroName – gcc –D macroName=definition • macros can be defined without giving them a specific value, e.g.: – #define macroName 20 line1 … linen will be included if identifier has been defined as a macro; otherwise nothing will happen.
  • 21. Conditional Compilation: #ifndef #ifndef identifier line1 … linen #endif 21 line1 … linen will be included if identifier is NOT defined as a macro; otherwise nothing will happen.
  • 22. Solution to multiple inclusion problem The header file is written as follows: #ifndef file_specific_flag #define file_specific_flag …contents of file… #endif • file_specific_flag usually constructed from the name of the header file: E.g.: file = foo.h ⇒ flag = _FOO_H_ – try to avoid macro names starting with ‘_’ 22 indicates whether or not this file has been included already
  • 23. Another use of #ifdefs • They can be useful for controlling debugging output – Example 1: guard debugging code with #ifdefs: #ifdef DEBUG …debug message… #endif – Example 2: use the debug macro to control what debugging code appears in the program: #ifdef DEBUG #define DMSG(msg) printf(msg) // debugging output #else #define DMSG(msg) {} // empty statement #endif 23 straightforward, but needs discipline to use consistently
  • 24. Generalizing #ifdef #if constant-expression line1 … linen #endif ⇒ line1 … linen included if constant-expression evaluates to a non-zero value 24 Common uses: • #if 1 or • #if 0
  • 25. __LINE__ current line number of the source file __FILE__ name of the current source file __TIME__ time of translation __STDC__ 1 if the compiler conforms to ANSI C printf("working on %sn", __FILE__); Predefined Macros
  • 26. Adapted originally from: CSc 352 An Introduction to the C Preprocessor Saumya Debray Dept. of Computer Science The University of Arizona, Tucson debray@cs.arizona.edu Thank you This presentation is created using LibreOffice Impress 3.6.2.2