Anda di halaman 1dari 3

11/7/2014

Preprocessor directives - C++ Tutorials


Search:

Go
Notloggedin

Tutorials

C++Language

Preprocessordirectives

register

login

C++
Inform ation
Tutorials
Reference
Articles
Forum

YouareusingaversionwithoutAdsofthiswebsite.Please,considerdonating:

[hide]

Tutorials
C++Language
AsciiCodes
BooleanOperations
NumericalBases

C++Language
Introduction:
Com pilers
BasicsofC++:
Structureofaprogram
Variablesandtypes
Constants
Operators
BasicInput/Output
Programstructure:
Statementsandflow control
Functions
Overloadsandtemplates
Namevisibility
Compounddatatypes:
Arrays
Charactersequences
Pointers
Dynamicmemory
Datastructures
Otherdatatypes
Classes:
Classes(I)
Classes(II)
Specialmembers
Friendshipandinheritance
Polymorphism
Otherlanguagefeatures:
Typeconversions
Exceptions
Preprocessordirectives
Standardlibrary:
Input/outputw ithfiles

Preprocessordirectives
Preprocessordirectivesarelinesincludedinthecodeofprogramsprecededbyahashsign(#).Theselinesarenotprogram
statementsbutdirectivesforthepreprocessor.Thepreprocessorexaminesthecodebeforeactualcompilationofcodebeginsand
resolvesallthesedirectivesbeforeanycodeisactuallygeneratedbyregularstatements.
Thesepreprocessordirectivesextendonlyacrossasinglelineofcode.Assoonasanewlinecharacterisfound,thepreprocessor
directiveisends.Nosemicolon(;)isexpectedattheendofapreprocessordirective.Theonlywayapreprocessordirectivecan
extendthroughmorethanonelineisbyprecedingthenewlinecharacterattheendofthelinebyabackslash(\).

macrodefinitions(#define,#undef)
Todefinepreprocessormacroswecanuse#define.Itssyntaxis:
#define identifier replacement
Whenthepreprocessorencountersthisdirective,itreplacesanyoccurrenceofidentifierintherestofthecodebyreplacement.
Thisreplacementcanbeanexpression,astatement,ablockorsimplyanything.ThepreprocessordoesnotunderstandC++
proper,itsimplyreplacesanyoccurrenceofidentifierbyreplacement.
1#define TABLE_SIZE 100
2int table1[TABLE_SIZE];
3int table2[TABLE_SIZE];

AfterthepreprocessorhasreplacedTABLE_SIZE,thecodebecomesequivalentto:
1int table1[100];
2int table2[100];

#definecanworkalsowithparameterstodefinefunctionmacros:
#define getmax(a,b) a>b?a:b

Thiswouldreplaceanyoccurrenceofgetmaxfollowedbytwoargumentsbythereplacementexpression,butalsoreplacingeach
argumentbyitsidentifier,exactlyasyouwouldexpectifitwasafunction:
1// function macro
2#include <iostream>
3using namespace std;
4
5#define getmax(a,b) ((a)>(b)?(a):(b))
6
7int main()
8{
9 int x=5, y;
10 y= getmax(x,2);
11 cout << y << endl;
12 cout << getmax(7,x) << endl;
13 return 0;
14}

5
7

Edit
&
Run

Definedmacrosarenotaffectedbyblockstructure.Amacrolastsuntilitisundefinedwiththe#undefpreprocessordirective:
1#define TABLE_SIZE 100
2int table1[TABLE_SIZE];
3#undef TABLE_SIZE
4#define TABLE_SIZE 200
5int table2[TABLE_SIZE];

Thiswouldgeneratethesamecodeas:
1int table1[100];
2int table2[200];

Functionmacrodefinitionsaccepttwospecialoperators(#and##)inthereplacementsequence:
Iftheoperator#isusedbeforeaparameterisusedinthereplacementsequence,thatparameterisreplacedbyastringliteral(asifit
wereenclosedbetweendoublequotes)
1#define str(x) #x
2cout << str(test);

Thiswouldbetranslatedinto:
cout << "test";

Theoperator##concatenatestwoargumentsleavingnoblankspacesbetweenthem:
1#define glue(a,b) a ## b

http://www.cplusplus.com/doc/tutorial/preprocessor/

1/3

11/7/2014

Preprocessor directives - C++ Tutorials


2glue(c,out) << "test";

Thiswouldalsobetranslatedinto:
cout << "test";

BecausepreprocessorreplacementshappenbeforeanyC++syntaxcheck,macrodefinitionscanbeatrickyfeature.But,becareful:
codethatreliesheavilyoncomplicatedmacrosbecomelessreadable,sincethesyntaxexpectedisonmanyoccasionsdifferentfrom
thenormalexpressionsprogrammersexpectinC++.

Conditionalinclusions(#ifdef,#ifndef,#if,#endif,#elseand#elif)
Thesedirectivesallowtoincludeordiscardpartofthecodeofaprogramifacertainconditionismet.
#ifdefallowsasectionofaprogramtobecompiledonlyifthemacrothatisspecifiedastheparameterhasbeendefined,nomatter
whichitsvalueis.Forexample:
1#ifdef TABLE_SIZE
2int table[TABLE_SIZE];
3#endif

Inthiscase,thelineofcodeint table[TABLE_SIZE];isonlycompiledifTABLE_SIZEwaspreviouslydefinedwith#define,
independentlyofitsvalue.Ifitwasnotdefined,thatlinewillnotbeincludedintheprogramcompilation.
#ifndefservesfortheexactopposite:thecodebetween#ifndefand#endifdirectivesisonlycompiledifthespecifiedidentifier
hasnotbeenpreviouslydefined.Forexample:
1#ifndef TABLE_SIZE
2#define TABLE_SIZE 100
3#endif
4int table[TABLE_SIZE];

Inthiscase,ifwhenarrivingatthispieceofcode,theTABLE_SIZEmacrohasnotbeendefinedyet,itwouldbedefinedtoavalueof
100.Ifitalreadyexisteditwouldkeepitspreviousvaluesincethe#definedirectivewouldnotbeexecuted.
The#if,#elseand#elif(i.e.,"elseif")directivesservetospecifysomeconditiontobemetinorderfortheportionofcodethey
surroundtobecompiled.Theconditionthatfollows#ifor#elifcanonlyevaluateconstantexpressions,includingmacro
expressions.Forexample:
1#if TABLE_SIZE>200
2#undef TABLE_SIZE
3#define TABLE_SIZE 200
4
5#elif TABLE_SIZE<50
6#undef TABLE_SIZE
7#define TABLE_SIZE 50
8
9#else
10#undef TABLE_SIZE
11#define TABLE_SIZE 100
12#endif
13
14int table[TABLE_SIZE];

Noticehowtheentirestructureof#if,#elifand#elsechaineddirectivesendswith#endif.
Thebehaviorof#ifdefand#ifndefcanalsobeachievedbyusingthespecialoperatorsdefinedand!definedrespectivelyin
any#ifor#elifdirective:
1#if defined ARRAY_SIZE
2#define TABLE_SIZE ARRAY_SIZE
3#elif !defined BUFFER_SIZE
4#define TABLE_SIZE 128
5#else
6#define TABLE_SIZE BUFFER_SIZE
7#endif

Linecontrol(#line)
Whenwecompileaprogramandsomeerrorhappensduringthecompilingprocess,thecompilershowsanerrormessagewith
referencestothenameofthefilewheretheerrorhappenedandalinenumber,soitiseasiertofindthecodegeneratingtheerror.
The#linedirectiveallowsustocontrolboththings,thelinenumberswithinthecodefilesaswellasthefilenamethatwewantthat
appearswhenanerrortakesplace.Itsformatis:
#line number "filename"
Wherenumberisthenewlinenumberthatwillbeassignedtothenextcodeline.Thelinenumbersofsuccessivelineswillbe
increasedonebyonefromthispointon.
"filename"isanoptionalparameterthatallowstoredefinethefilenamethatwillbeshown.Forexample:
1#line 20 "assigning variable"
2int a?;

Thiscodewillgenerateanerrorthatwillbeshownaserrorinfile"assigning variable",line20.

Errordirective(#error)
Thisdirectiveabortsthecompilationprocesswhenitisfound,generatingacompilationerrorthatcanbespecifiedasitsparameter:

http://www.cplusplus.com/doc/tutorial/preprocessor/

2/3

11/7/2014

Preprocessor directives - C++ Tutorials


1#ifndef __cplusplus
2#error A C++ compiler is required!
3#endif

Thisexampleabortsthecompilationprocessifthemacroname__cplusplusisnotdefined(thismacronameisdefinedbydefault
inallC++compilers).

Sourcefileinclusion(#include)
Thisdirectivehasbeenusedassiduouslyinothersectionsofthistutorial.Whenthepreprocessorfindsan#includedirectiveit
replacesitbytheentirecontentofthespecifiedheaderorfile.Therearetwowaystouse#include:
1#include <header>
2#include "file"

Inthefirstcase,aheaderisspecifiedbetweenanglebrackets<>.Thisisusedtoincludeheadersprovidedbytheimplementation,
suchastheheadersthatcomposethestandardlibrary(iostream,string,...).Whethertheheadersareactuallyfilesorexistinsome
otherformisimplementationdefined,butinanycasetheyshallbeproperlyincludedwiththisdirective.
Thesyntaxusedinthesecond#includeusesquotes,andincludesafile.Thefileissearchedforinanimplementationdefined
manner,whichgenerallyincludesthecurrentpath.Inthecasethatthefileisnotfound,thecompilerinterpretsthedirectiveasa
headerinclusion,justasifthequotes("")werereplacedbyanglebrackets(<>).

Pragmadirective(#pragma)
Thisdirectiveisusedtospecifydiverseoptionstothecompiler.Theseoptionsarespecificfortheplatformandthecompileryouuse.
Consultthemanualorthereferenceofyourcompilerformoreinformationonthepossibleparametersthatyoucandefinewith
#pragma.
Ifthecompilerdoesnotsupportaspecificargumentfor#pragma,itisignorednosyntaxerrorisgenerated.

Predefinedmacronames
Thefollowingmacronamesarealwaysdefined(theyallbeginandendwithtwounderscorecharacters,_):
macro
__LINE__
__FILE__
__DATE__
__TIME__

value
Integervaluerepresentingthecurrentlineinthesourcecodefilebeingcompiled.
Astringliteralcontainingthepresumednameofthesourcefilebeingcompiled.
Astringliteralintheform"Mmmddyyyy"containingthedateinwhichthecompilationprocessbegan.
Astringliteralintheform"hh:mm:ss"containingthetimeatwhichthecompilationprocessbegan.
Anintegervalue.AllC++compilershavethisconstantdefinedtosomevalue.Itsvaluedependsontheversionof
thestandardsupportedbythecompiler:
199711L:ISOC++1998/2003
201103L:ISOC++2011

__cplusplus

Nonconformingcompilersdefinethisconstantassomevalueatmostfivedigitslong.Notethatmanycompilers
arenotfullyconformingandthuswillhavethisconstantdefinedasneitherofthevaluesabove.
1iftheimplementationisahostedimplementation(withallstandardheadersavailable)
__STD_HOSTED__
0otherwise.
Thefollowingmacrosareoptionallydefined,generallydependingonwhetherafeatureisavailable:
macro
__STDC__

value
InC:ifdefinedto1,theimplementationconformstotheCstandard.
InC++:Implementationdefined.
InC:
199401L:ISOC1990,Ammendment1
199901L:ISOC1999
201112L:ISOC2011

__STDC_VERSION__

InC++:Implementationdefined.
1ifmultibyteencodingmightgiveacharacteradifferentvalueincharacterliterals
AvalueintheformyyyymmL,specifyingthedateoftheUnicodestandardfollowedbythe
__STDC_ISO_10646__
encodingofwchar_tcharacters
__STDCPP_STRICT_POINTER_SAFETY__1iftheimplementationhasstrictpointersafety(seeget_pointer_safety)
__STDCPP_THREADS__
1iftheprogramcanhavemorethanonethread
__STDC_MB_MIGHT_NEQ_WC__

Particularimplementationsmaydefineadditionalconstants.
Forexample:

1// standard macro names


This is the line number 7 of file /home/jay/stdmacroname
2#include <iostream>
Its compilation began Nov 1 2005 at 10:12:29.
3using namespace std;
The compiler gives a __cplusplus value of 1
4
5int main()
6{
7 cout << "This is the line number " << __LINE__;
8 cout << " of file " << __FILE__ << ".\n";
9 cout << "Its compilation began " << __DATE__;
10 cout << " at " << __TIME__ << ".\n";
11 cout << "The compiler gives a __cplusplus value of " << __cplusplus;
12 return 0;
13}

Previous:
Exceptions

Index

Next:
Input/outputwithfiles

Homepage|Priv acy policy


cplusplus.com,20002014Allrightsreserv edv3.1
Spottedanerror?contactus

http://www.cplusplus.com/doc/tutorial/preprocessor/

3/3

Anda mungkin juga menyukai