Sie sind auf Seite 1von 8

11/7/2014

C++ Preprocessor Directives | CodingUnit Programming Tutorials

Home
About
Search
rssposts

C++PreprocessorDirectives
InthisC++programmingtutorialwewilllookatcompilingandpreprocessordirectives.WheneveraCPP
programiscompiledthenthefollowingstepsaretaken:

Thepreprocessorisautilityprogram,whichprocessesspecialinstructionsthatcanbeorarewrittenina
C/CPPprogram.Theseinstructionscanbeincludealibraryorsomespecialinstructionstothecompilerabout
somecertaintermsusedintheprogram.
Preprocessordirectivesstartwith#character.
Differentpreprocessordirectives(commands)performdifferenttasks.WecancategorizethePreprocessor
Directivesasfollows:
InclusionDirectives
MacroDefinitionDirectives
ConditionalCompilationDirectives
OtherDirectives

InclusionDirective
Thiscategoryhasonlyonedirective,whichiscalled#include.Thisinclusiondirectiveisusedtoincludefilesinto
http://www.codingunit.com/cplusplus-tutorial-preprocessor-directives

1/8

11/7/2014

C++ Preprocessor Directives | CodingUnit Programming Tutorials

thecurrentfile.Theinclusiondirectivecanbeusedasfollows:
#include<stdio.h>

includesstdio.hfrominclude
folder

#include<iostream>

includescppclasslibraryheader
iostream

#include<my.cpp>

includesmy.cppfilefrominclude
folder

#include my.h

includesmy.hfilefromcurrentworking
folder

#include myfolder/abc.h

includesabc.hfilefromthemyfolderwhich
isavailableincurrentworkingfolder

Fromtheaboveusagetablewecanseethat#includeisusedwithtwooptionsangularbrackets(<>)and
invertedcommas().When#includeiswrittenwith<>itmeansweareinstructingtoincludethefilesfromthe
includepathdefinedinthecompilersettingswhichisgenerallytheincludefolderfromthecompiler.When
#includeiswrittenwithitmeansweareinstructingtoincludeafile:firstthecurrentfolderischeckedandifitis
notfoundthere,thentheincludefolderofthecompilerischecked.
Takealookatasimpleexample.Savethefollowingcodeinafilecalledmain.c:
#include<stdio.h>
#include "header.h"
int main() {

printf("The variable from the header file: a = %d", a);


return 0;

Thensavethecodebelowinafilecalledheader.handplaceitinthesamedirectoryasmain.c:
#ifndef __mynamespace__
int a = 10;
#endif

Thevariabledeclaredintheheader.hfilewillbeincludedinmain.c,sowecanusethevariableinmain().

MacroDefinitionDirectives
Theseareusedtodefinemacros,whichareone,ormoreprogramstatements(likefunctions)andtheyare
expandedinline.(Expandedinlinemeanstheyaresubstitutedattheplaceofmacrocallunlikefunctionsinwhich
theexecutionpointermovestothefunctiondefinition.).
TherearetwodirectivesforMacroDefinition:
http://www.codingunit.com/cplusplus-tutorial-preprocessor-directives

2/8

11/7/2014

C++ Preprocessor Directives | CodingUnit Programming Tutorials

#defineUsedtodefineamacro
#undefUsedtoundefineamacro(Themacrocannotbeusedafteritisundefined.)
Takealookattheexample,whichisusingincludedirectiveandsomemacrodefinitiondirectives:
#include <iostream>
using namespace std;
#define PI 3.14
#define SQR(X) ((X)* (X))
#define CUBE(y) SQR(y)* (y)
int main(int argc,char *argv[])
{
int radius;
cout << endl << "Enter Radius of the Circle:"; cin >> radius;
cout << endl << "Area of the Circle is: " << PI * SQR(radius);
#undef PI
//It is now
invalid to use PI, thus we cannot use the next line.
//cout << endl << "Perimeter of Circle is : " << 2 * PI * radius;

cout << endl << "Area of the Sphere of Radius " << \
radius << " is: " << 4/3.0 * 3.14 * CUBE(radius);

Theaboveexampleillustratesthefollowing:
Wedonotterminatethemacrosusing()
Macroscanbeparameterized
Macroscanbedependentonothermacros(mustbedefinedbeforetheyareused.)
Macrosarecustomarilywrittenincapitalletterstoavoidconfusionbetweenmacroandfunctions.(thisis
notarule)
Parametersareenclosedin()toavoidtheambiguityarisingduetooperatorprecedence.Forinstancein
theexampleabovewecallSQR(4+3).Thisstatementwillbeexpandedas(4+3)*(4+3).
Directivesarehelpfulwheneverthingsarepronetochangesandareusedatmanyplacesinoneprogram.
Changingthedirectivevalueatthetopwillcausethecorrespondingchangesatalltheplacesinthe
program.
Ifthedirectiverequiresuseofmorethanonelinethenitcanbecontinuedinthenextlineafterplacing\atthe
endofthefirstline.
Takealookatthefollowingexample:
#include <iostream>
using namespace std;
#define greater(m,n)(m>n) ? (m) \
: (n);
int main(int argc, char *argv[])
{
http://www.codingunit.com/cplusplus-tutorial-preprocessor-directives

3/8

11/7/2014

C++ Preprocessor Directives | CodingUnit Programming Tutorials

int number1, number2;


cout << endl << "Enter two numbers:";
cin >> number1 >> number2;

int g = greater(number1, number2);


cout << endl << "Greater of the two numbers is: " << g;

ConditionalCompilationDirectives
ConditionalCompilationDirectivestheseareusedtoexecutestatementsconditionallyfor:
Executingthecodeondifferentmachinearchitectures.
Debuggingpurposes.
Macroscanbedependentonothermacros(mustbedefinedbeforetheyareused.)
Evaluatingcodes,whicharetobeexecuteddependingupontherequirementsoftheprogrammer.
Thefollowingdirectivesareincludedinthiscategory:
#if
#elif
#endif
#ifdef
#ifndef
Note:Thesemacrosareevaluatedoncompiletime.Thereforetheycanonlyusethepredefinedmacrosor
literals.Mostcompilersdonotsupporttheuseofvariableswiththesedirectives.
#include <iostream>
using namespace std;
#define US 0
#define ENGLAND 1
#define NETHERLANDS 2
//We define Netherlands as country, then we get Euro.
//If we define England we get pounds and so on.
#define CURRENCY NETHERLANDS
int main(int argc, char *argv[])
{
#if CURRENCY == US
char acurrency[] = {"Dollar"};
#define CHOSEN US
#elif CURRENCY == ENGLAND
char acurrency[] = { "Pound" };
#define CHOSEN ENGLAND
#elif CURRENCY == NETHERLANDS
char acurrency[] = { "Euro" };
#define CHOSEN NETHERLANDS
#else
char acurrency[] = {"Euro"};
http://www.codingunit.com/cplusplus-tutorial-preprocessor-directives

4/8

11/7/2014

C++ Preprocessor Directives | CodingUnit Programming Tutorials

#endif
// If CHOSEN is not defined, then we get default.
#ifndef CHOSEN
cout << endl << "Using Default Currency " << acurrency;
#else
cout << endl << "Chosen Currency " << acurrency;
#endif

OtherDirectives
Thefollowingdirectivesaretheotherdirectives:
#error
#line
#pragma

#error
Whenthe#errordirectiveisfoundtheprogramwillbeterminatedandthemessage(thatisgivenafterthe#error
statement)willbeusedinthecompilationerrorthatisgivenbythecompiler.
Takealookatanexample:
#ifndef __cplusplus
#error Compilation Error: A C++ compiler is required to compile this program!
#endif

The__plusplusmacroisbydefaultdefinedbymostC++compilers.Soifthismacroisnotfound,during
compilation,thenthecompilationisabortedandthemessage(CompilationError:AC++compilerisrequiredto
compilethisprogram!)isprintedfortheuser.

#line
The#linedirectiveisusedtochangethevalueofthe__LINE__and__FILE__macros.(Note:thefilenameis
optional.)The__LINE__and__FILE__macrosrepresentthelinebeingreadandthefilebeingread.
#line 50 "myfile.cpp"

Thiswillsetthe__LINE__to50and__FILE__tomyfile.cpp

#pragma
The#pragmadirectiveisusedtoallowsuppressionofspecificerrormessages,manageheapandstack
debugging,etc.Thesearecompilerspecificdirectives.(Checkyourcompilerdocumentationforthe#pragma
linesyoucanuse.)
http://www.codingunit.com/cplusplus-tutorial-preprocessor-directives

5/8

11/7/2014

C++ Preprocessor Directives | CodingUnit Programming Tutorials

ForExample#pragmainlinestatementindicatestheassemblycodeisavailableinthecode.
Ifthedirectiveisunavailableinanimplementationthestatementisignored.

PredefinedMacros
__LINE__
Anintegerthatgivesthelinenumberofthecurrentsourcefilebeingcompiled.

__FILE__
Astringthatgivesthenameofthesourcefilebeingcompiled.

__DATE__
Astringthatgivesthedate,intheformMmmddyyyy,whenthecompilationprocessbegan.

__TIME__
Astringconstantthatgivesthetimeatwhichthepreprocessorisbeingrun.Thestringconstantlookslike
22:05:02andcontainseightcharacters.Ifthecompilercannotdeterminethecurrenttime,itwillgiveawarning
messageand__TIME__willbeexpandedto??:??:??.Note:thewarningwillonlybegivenonceper
compilation.

__STDC__
ForcestheuseofstandardC/CPPcodesonlyintheprogram.

__cplusplus
Containsa6digitnumbertoindicatethatthecompilerisbasedonthestandards,otherwiseitcontains5orfewer
digits.

__ASSEMBLER__
Thismacroisdefinedwithavalueof1whenpreprocessingassemblylanguage.

__OBJC__
Ifthismacroisdefinedwithavalueof1thentheObjectiveCcompilerisinuse.Thismacrocanbeusedtotest
whetheraheaderfileiscompiledbyaCcompileroranObjectiveCcompiler.
Thatisallforthistutorial.
http://www.codingunit.com/cplusplus-tutorial-preprocessor-directives

6/8

11/7/2014

C++ Preprocessor Directives | CodingUnit Programming Tutorials

ThisentrywaspostedinC++Tutorials.YoucanfollowanyresponsestothisentrythroughtheRSS2.0feed.Bothcomments
andpingsarecurrentlyclosed.

TweetThis!oruse

ShareThis tosharethispostwithothers.

Therearecurrently3responsestoC++PreprocessorDirectives
Whynotletusknowwhatyouthinkbyaddingyourowncomment!
1. sambaonJanuary23rd,2013:
good
2. ZwergsockeonApril27th,2014:
nicework
butIbeliveyoumadeamistakewiththePredefinedMacrosIthinkthemacro__TIME__shouldgive
youtheTimewhenthecompilationprocessbeganandnotthenameofthesourcefile..
3. adminonApril27th,2014:
@Zwergsocke,THXIvechangedthecopy/pasteerror.The__TIME__macroisnowcorrect!
uptocontent

C++Tutorials
HistoryoftheC++language
C++Compilers(GNUandVisualStudio)
FirstC++program,helloworld
C++VariablesandDataTypes
C++constants,escapecodesandstrings
C++operators,compoundassignments
C++StandardI/Ocinandcout
C++StandardI/Oandstrings
C++Theifstatementandswitchstatement
C++forloops,whileloops
C++Usingfunctions,functionparameters
C++Functionsandcommandlineparameters
C++arrays,arraysandloops
C++Charactersequenceusingarrays
C++pointersreferenceanddereferenceoperators
C++DynamicMemory
C++structures,typedefandunions
C++Classes
C++ClassesConstructorsanddestructors
FileIOinC++(textandbinaryfiles)
FileIOinC++(textandbinaryfiles)partII
C++TutorialNamespacesandanonymousnamespaces
C++OverloadingandOperatorOverloading
C++Unaryandbinaryoperatoroverloadingandstaticmembers
http://www.codingunit.com/cplusplus-tutorial-preprocessor-directives

7/8

11/7/2014

C++ Preprocessor Directives | CodingUnit Programming Tutorials

C++Inheritance
C++FriendfunctionandFriendclass
C++Templates
C++PolymorphismandAbstractBaseClass
C++Exceptionsandexceptionhandling
C++TypecastingPart1
C++TypecastingPart2RTTI,dynamic_cast,typeidandtype_info
C++PreprocessorDirectives
C++BinaryOperatorOverloadingGreaterorLessthan

LatestPosts
CTutorialQueues
CTutorialErrorHandling(ExceptionHandling)
CTutorialSplittingaTextFileintoMultipleFiles
CTutorialDeletingaRecordfromaBinaryFile
CTutorialCallbyValueorCallbyReference
CheckingforPalindromeStringsorNumbersinCLanguage
LinearSearchAlgorithminCLanguage
DeterminingtheAreaofDifferentShapedTrianglesinC
AreaofaRectangleCircleandTrapeziuminC
HowtoPrintFloydsTriangleinC

2014CodingUnitProgrammingTutorials.AllRightsReserved.|Contact
TERMSandPrivacyPolicyUNDERWHICHTHISSERVICEISPROVIDEDTOYOU.

http://www.codingunit.com/cplusplus-tutorial-preprocessor-directives

8/8

Das könnte Ihnen auch gefallen