SlideShare a Scribd company logo
1 of 3
Download to read offline
TECHINICAL REPORT ON C/C++ PREPROCESSOR
RECURSIVE MACRO EXPANSION
Abstract
C/C++ is one of a old programming language which could not be survived without a preprocessor.
However there are some pitfalls on it’s preprocessor. They are actually not pitfalls, but it’s how that
original C/C++ preprocessor is designed to be. Anyway a newbie programmer may get get confused
due to it. I also ran into this trouble at once. At that time I was doing my final year project, and I have
asked it on http://stackoverfow.com/ and get retrieved a fix to the problem. But that time I didn’t have
precisely understood which magic does the trick.
Case Study
Think that you have to write a macro called `TRACE`. When running on __DEBUG__ defined it
should print line number and filename (ex- database.cpp line 2156) when executed through it. This is
mainly used for debugging purposes.
For a example like bellow you could use `TRACE`.
#ifdef __DEBUG__
#define TRACE 
PrintErrorMsg("Trace exception in " __FILE__ 
" at line number " #__LINE__ 
);
#else
Simply the problem is `__LINE__` will expanded into a integer literal, so it is not concentrate with
the c-string literal on left hand side, so compiler emits an error.
error: cannot convert 'const char*' to 'FILE* {aka _iobuf*}' for argument '1' to
'int fprintf(FILE*, const char*, ...)'
So I do need to convert the integer literal into a c-string literal. The easiest way to do is the stringizing
operator in maco-preprocessor.
I have quoted bellow a stringizing example from MSDN website.
// stringizer.cpp
#include <stdio.h>
#define stringer( x ) printf_s( #x "n" )
int main() {
stringer( In quotes in the printf function call );
stringer( "In quotes when printed to the screen" );
stringer( "This: " prints an escaped double quote" );
}
So according to that we could rewrite our `TRACE` macro like bellow.
#ifdef __DEBUG__
#define TRACE 
PrintErrorMsg("Trace exception in " __FILE__ 
" at line number " #__LINE__ 
);
#else
But the output is “Trace exception in database.cpp at line number __LINE__”. At that time I was
pressured to finish the project and handover the dissertation so I didn’t had time to find out what’s
going on? So the lazy minded man have fired a question on stackoverflow.
http://stackoverflow.com/questions/13301428/token-pasting-and-line
However then I fix my project codebase with following codes, By replace our `TRACE’ like bellow.
#define STRINGIZE(x) STRINGIZE_SIMPLE(x)
#define STRINGIZE_SIMPLE(x) #x
#ifdef __DEBUG__
#define TRACE 
PrintErrorMsg("Trace exception in " __FILE__ 
" at line number " STRINGIZE(__LINE__) 
);
#else
#ifdef TRACE
#undef TRACE
#endif
#endif
At that time this works like a dream to me. Now today I’m writing why the hell this is happening?
The secret lies behind how preprocessor expand it’s parameters.
Unfortunately I just fired up a very lazy duplicate question in stackoverflow , I have to apologize that
from all the contributors who read my question.
Anyway, I’m not the only one who made a duplicate. Then I have navigated into those questions and
explore why this is happening.
http://stackoverflow.com/questions/4284733/preprocessor-token-expansion#_=_
http://stackoverflow.com/questions/1597007/creating-c-macro-with-and-line-token-concatenation-
with-positioning-macr
So according to the accepted answer, it’s said.
the preprocessor will only expand the macros recursively if neither the stringizing
operator # nor the token-pasting operator ## are applied to it. So, you have to use
some extra layers of indirection, you can use the token-pasting operator with a
recursively expanded argument.
So now it’s much more clear.
Let me explain how this is happening….
Since `#__LINE__` is just a stringizing operator so it won’t reclusively be expanded. So the output
will be “__LINE__”.
So we need some recursive invocation, like this,
#define STRINGIZING(X) #X
This won’t work either, because `__LINE__` will be passed as X, and there is #X , so in this line
`__LINE__` would not be expanded at all.
But if we passed it to another nested macro like bellow,
#define STRINGIZING(X) STRINGIZING2(X)
Then incoming parameter `X` will be expanded to `__LINE__` and again `__LINE__` will be
expanded into whatever the line number remembered by the compiler. Say that 2326 was passed like
bellow , then
STRINGIZING2(2326)
will be called. After expansions were done.
So in the next nested macro it would be like,
#define STRINGIZING(X) #X
Where it does not hold `__LINE__` ,but integer literal `2326`. It was expanded because we don’t have
stringizing operator at STRINGIZING(X) macro definition. [ #define STRINGIZING(X)
STRINGIZING2(X) , so it get expanded ].
So that’s where the magic came from. Actually it’s not magic, it’s the preprocessors expected
behavior, only thing we need to explicitly force `__LINE__` to be expanded.
Hope you understand the document and thanks for reading.

More Related Content

What's hot (16)

[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
 
Analyzing Firebird 3.0
Analyzing Firebird 3.0Analyzing Firebird 3.0
Analyzing Firebird 3.0
 
Design problem
Design problemDesign problem
Design problem
 
15 practical grep command examples in linux : unix
15 practical grep command examples in linux : unix15 practical grep command examples in linux : unix
15 practical grep command examples in linux : unix
 
How to make fewer errors at the stage of code writing. Part N4.
How to make fewer errors at the stage of code writing. Part N4.How to make fewer errors at the stage of code writing. Part N4.
How to make fewer errors at the stage of code writing. Part N4.
 
[ITP - Lecture 13] Introduction to Pointers
[ITP - Lecture 13] Introduction to Pointers[ITP - Lecture 13] Introduction to Pointers
[ITP - Lecture 13] Introduction to Pointers
 
First Class
First ClassFirst Class
First Class
 
07_triangle_pattern.pdf
07_triangle_pattern.pdf07_triangle_pattern.pdf
07_triangle_pattern.pdf
 
PVS-Studio vs Clang
PVS-Studio vs ClangPVS-Studio vs Clang
PVS-Studio vs Clang
 
08_pyramid_pattern.pdf
08_pyramid_pattern.pdf08_pyramid_pattern.pdf
08_pyramid_pattern.pdf
 
Text expansion in vim
Text expansion in vimText expansion in vim
Text expansion in vim
 
[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types
 
Chowtodoprogram solutions
Chowtodoprogram solutionsChowtodoprogram solutions
Chowtodoprogram solutions
 
1 introducing c language
1  introducing c language1  introducing c language
1 introducing c language
 
Lecture 12 - Recursion
Lecture 12 - Recursion Lecture 12 - Recursion
Lecture 12 - Recursion
 
Programming basics
Programming basicsProgramming basics
Programming basics
 

Viewers also liked

IMP questions for System programming for GTU
IMP questions for System programming for GTUIMP questions for System programming for GTU
IMP questions for System programming for GTUParas Patel
 
Cp0675 03 may-2012-rm04
Cp0675 03 may-2012-rm04Cp0675 03 may-2012-rm04
Cp0675 03 may-2012-rm04Parth Mudgal
 
Introdução ao editor de texto Word
Introdução ao editor de texto WordIntrodução ao editor de texto Word
Introdução ao editor de texto WordDaniel Brandão
 
what is compiler and five phases of compiler
what is compiler and five phases of compilerwhat is compiler and five phases of compiler
what is compiler and five phases of compileradilmehmood93
 
Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingPhases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingMukesh Tekwani
 
phases of compiler-analysis phase
phases of compiler-analysis phasephases of compiler-analysis phase
phases of compiler-analysis phaseSuyash Srivastava
 

Viewers also liked (11)

IMP questions for System programming for GTU
IMP questions for System programming for GTUIMP questions for System programming for GTU
IMP questions for System programming for GTU
 
Cp0675 03 may-2012-rm04
Cp0675 03 may-2012-rm04Cp0675 03 may-2012-rm04
Cp0675 03 may-2012-rm04
 
Introdução ao editor de texto Word
Introdução ao editor de texto WordIntrodução ao editor de texto Word
Introdução ao editor de texto Word
 
Ss4
Ss4Ss4
Ss4
 
Vi editor
Vi   editorVi   editor
Vi editor
 
Pass 1 flowchart
Pass 1 flowchartPass 1 flowchart
Pass 1 flowchart
 
Macro
MacroMacro
Macro
 
what is compiler and five phases of compiler
what is compiler and five phases of compilerwhat is compiler and five phases of compiler
what is compiler and five phases of compiler
 
Phases of Compiler
Phases of CompilerPhases of Compiler
Phases of Compiler
 
Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingPhases of the Compiler - Systems Programming
Phases of the Compiler - Systems Programming
 
phases of compiler-analysis phase
phases of compiler-analysis phasephases of compiler-analysis phase
phases of compiler-analysis phase
 

Similar to C/C++ PREPROCESSOR MACRO RECURSION

Tips and Tricks using the Preprocessor
Tips and Tricks using the Preprocessor Tips and Tricks using the Preprocessor
Tips and Tricks using the Preprocessor skbansal222
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Andrey Karpov
 
Checking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameChecking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameAndrey Karpov
 
05 -working_with_the_preproce
05  -working_with_the_preproce05  -working_with_the_preproce
05 -working_with_the_preproceHector Garzo
 
(8) cpp abstractions separated_compilation_and_binding_part_i
(8) cpp abstractions separated_compilation_and_binding_part_i(8) cpp abstractions separated_compilation_and_binding_part_i
(8) cpp abstractions separated_compilation_and_binding_part_iNico Ludwig
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project AnalyzedPVS-Studio
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?PVS-Studio
 
Miranda NG Project to Get the "Wild Pointers" Award (Part 1)
Miranda NG Project to Get the "Wild Pointers" Award (Part 1) Miranda NG Project to Get the "Wild Pointers" Award (Part 1)
Miranda NG Project to Get the "Wild Pointers" Award (Part 1) Andrey Karpov
 
How to make fewer errors at the stage of code writing. Part N1.
How to make fewer errors at the stage of code writing. Part N1.How to make fewer errors at the stage of code writing. Part N1.
How to make fewer errors at the stage of code writing. Part N1.PVS-Studio
 
What comments hide
What comments hideWhat comments hide
What comments hidePVS-Studio
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and BeyondComicSansMS
 
PVS-Studio vs Chromium
PVS-Studio vs ChromiumPVS-Studio vs Chromium
PVS-Studio vs ChromiumPVS-Studio
 
PVS-Studio vs Chromium
PVS-Studio vs ChromiumPVS-Studio vs Chromium
PVS-Studio vs ChromiumAndrey Karpov
 
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" DependenciesAnalyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" DependenciesPVS-Studio
 
Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016PVS-Studio
 
Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016PVS-Studio
 
LibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-StudioLibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-StudioAndrey Karpov
 

Similar to C/C++ PREPROCESSOR MACRO RECURSION (20)

Tips and Tricks using the Preprocessor
Tips and Tricks using the Preprocessor Tips and Tricks using the Preprocessor
Tips and Tricks using the Preprocessor
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...
 
Checking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameChecking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto Game
 
05 -working_with_the_preproce
05  -working_with_the_preproce05  -working_with_the_preproce
05 -working_with_the_preproce
 
(8) cpp abstractions separated_compilation_and_binding_part_i
(8) cpp abstractions separated_compilation_and_binding_part_i(8) cpp abstractions separated_compilation_and_binding_part_i
(8) cpp abstractions separated_compilation_and_binding_part_i
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?
 
Miranda NG Project to Get the "Wild Pointers" Award (Part 1)
Miranda NG Project to Get the "Wild Pointers" Award (Part 1) Miranda NG Project to Get the "Wild Pointers" Award (Part 1)
Miranda NG Project to Get the "Wild Pointers" Award (Part 1)
 
How to make fewer errors at the stage of code writing. Part N1.
How to make fewer errors at the stage of code writing. Part N1.How to make fewer errors at the stage of code writing. Part N1.
How to make fewer errors at the stage of code writing. Part N1.
 
What comments hide
What comments hideWhat comments hide
What comments hide
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
Preprocessors
PreprocessorsPreprocessors
Preprocessors
 
PVS-Studio vs Chromium
PVS-Studio vs ChromiumPVS-Studio vs Chromium
PVS-Studio vs Chromium
 
PVS-Studio vs Chromium
PVS-Studio vs ChromiumPVS-Studio vs Chromium
PVS-Studio vs Chromium
 
Oct.22nd.Presentation.Final
Oct.22nd.Presentation.FinalOct.22nd.Presentation.Final
Oct.22nd.Presentation.Final
 
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" DependenciesAnalyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
 
Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016
 
Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016
 
LibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-StudioLibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-Studio
 
C Programming Homework Help
C Programming Homework HelpC Programming Homework Help
C Programming Homework Help
 

More from Sandun Perera

0512575 printing request_and_press_resource_management_system_for_udara_type_...
0512575 printing request_and_press_resource_management_system_for_udara_type_...0512575 printing request_and_press_resource_management_system_for_udara_type_...
0512575 printing request_and_press_resource_management_system_for_udara_type_...Sandun Perera
 
Electrical power ecx3232 lab report
Electrical power ecx3232 lab reportElectrical power ecx3232 lab report
Electrical power ecx3232 lab reportSandun Perera
 
Modern computer virology
Modern computer virologyModern computer virology
Modern computer virologySandun Perera
 
File inflection techniques
File inflection techniquesFile inflection techniques
File inflection techniquesSandun Perera
 
Buffer overflow attacks
Buffer overflow attacksBuffer overflow attacks
Buffer overflow attacksSandun Perera
 
Buffer overflow attacks
Buffer overflow attacksBuffer overflow attacks
Buffer overflow attacksSandun Perera
 

More from Sandun Perera (7)

0512575 printing request_and_press_resource_management_system_for_udara_type_...
0512575 printing request_and_press_resource_management_system_for_udara_type_...0512575 printing request_and_press_resource_management_system_for_udara_type_...
0512575 printing request_and_press_resource_management_system_for_udara_type_...
 
Electrical power ecx3232 lab report
Electrical power ecx3232 lab reportElectrical power ecx3232 lab report
Electrical power ecx3232 lab report
 
Modern computer virology
Modern computer virologyModern computer virology
Modern computer virology
 
Buffer overflows
Buffer overflowsBuffer overflows
Buffer overflows
 
File inflection techniques
File inflection techniquesFile inflection techniques
File inflection techniques
 
Buffer overflow attacks
Buffer overflow attacksBuffer overflow attacks
Buffer overflow attacks
 
Buffer overflow attacks
Buffer overflow attacksBuffer overflow attacks
Buffer overflow attacks
 

Recently uploaded

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Recently uploaded (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

C/C++ PREPROCESSOR MACRO RECURSION

  • 1. TECHINICAL REPORT ON C/C++ PREPROCESSOR RECURSIVE MACRO EXPANSION Abstract C/C++ is one of a old programming language which could not be survived without a preprocessor. However there are some pitfalls on it’s preprocessor. They are actually not pitfalls, but it’s how that original C/C++ preprocessor is designed to be. Anyway a newbie programmer may get get confused due to it. I also ran into this trouble at once. At that time I was doing my final year project, and I have asked it on http://stackoverfow.com/ and get retrieved a fix to the problem. But that time I didn’t have precisely understood which magic does the trick. Case Study Think that you have to write a macro called `TRACE`. When running on __DEBUG__ defined it should print line number and filename (ex- database.cpp line 2156) when executed through it. This is mainly used for debugging purposes. For a example like bellow you could use `TRACE`. #ifdef __DEBUG__ #define TRACE PrintErrorMsg("Trace exception in " __FILE__ " at line number " #__LINE__ ); #else Simply the problem is `__LINE__` will expanded into a integer literal, so it is not concentrate with the c-string literal on left hand side, so compiler emits an error. error: cannot convert 'const char*' to 'FILE* {aka _iobuf*}' for argument '1' to 'int fprintf(FILE*, const char*, ...)' So I do need to convert the integer literal into a c-string literal. The easiest way to do is the stringizing operator in maco-preprocessor. I have quoted bellow a stringizing example from MSDN website. // stringizer.cpp #include <stdio.h> #define stringer( x ) printf_s( #x "n" ) int main() { stringer( In quotes in the printf function call ); stringer( "In quotes when printed to the screen" ); stringer( "This: " prints an escaped double quote" ); }
  • 2. So according to that we could rewrite our `TRACE` macro like bellow. #ifdef __DEBUG__ #define TRACE PrintErrorMsg("Trace exception in " __FILE__ " at line number " #__LINE__ ); #else But the output is “Trace exception in database.cpp at line number __LINE__”. At that time I was pressured to finish the project and handover the dissertation so I didn’t had time to find out what’s going on? So the lazy minded man have fired a question on stackoverflow. http://stackoverflow.com/questions/13301428/token-pasting-and-line However then I fix my project codebase with following codes, By replace our `TRACE’ like bellow. #define STRINGIZE(x) STRINGIZE_SIMPLE(x) #define STRINGIZE_SIMPLE(x) #x #ifdef __DEBUG__ #define TRACE PrintErrorMsg("Trace exception in " __FILE__ " at line number " STRINGIZE(__LINE__) ); #else #ifdef TRACE #undef TRACE #endif #endif At that time this works like a dream to me. Now today I’m writing why the hell this is happening? The secret lies behind how preprocessor expand it’s parameters. Unfortunately I just fired up a very lazy duplicate question in stackoverflow , I have to apologize that from all the contributors who read my question. Anyway, I’m not the only one who made a duplicate. Then I have navigated into those questions and explore why this is happening.
  • 3. http://stackoverflow.com/questions/4284733/preprocessor-token-expansion#_=_ http://stackoverflow.com/questions/1597007/creating-c-macro-with-and-line-token-concatenation- with-positioning-macr So according to the accepted answer, it’s said. the preprocessor will only expand the macros recursively if neither the stringizing operator # nor the token-pasting operator ## are applied to it. So, you have to use some extra layers of indirection, you can use the token-pasting operator with a recursively expanded argument. So now it’s much more clear. Let me explain how this is happening…. Since `#__LINE__` is just a stringizing operator so it won’t reclusively be expanded. So the output will be “__LINE__”. So we need some recursive invocation, like this, #define STRINGIZING(X) #X This won’t work either, because `__LINE__` will be passed as X, and there is #X , so in this line `__LINE__` would not be expanded at all. But if we passed it to another nested macro like bellow, #define STRINGIZING(X) STRINGIZING2(X) Then incoming parameter `X` will be expanded to `__LINE__` and again `__LINE__` will be expanded into whatever the line number remembered by the compiler. Say that 2326 was passed like bellow , then STRINGIZING2(2326) will be called. After expansions were done. So in the next nested macro it would be like, #define STRINGIZING(X) #X Where it does not hold `__LINE__` ,but integer literal `2326`. It was expanded because we don’t have stringizing operator at STRINGIZING(X) macro definition. [ #define STRINGIZING(X) STRINGIZING2(X) , so it get expanded ]. So that’s where the magic came from. Actually it’s not magic, it’s the preprocessors expected behavior, only thing we need to explicitly force `__LINE__` to be expanded. Hope you understand the document and thanks for reading.