Chapter3:WritingMakefiles
11
3 WritingMakefiles
Theinformationthattellsmakehowtorecompileasystemcomesfromreadingadatabase
calledthemakefile.
3.1 WhatMakefilesContain
Makefiles containfive kinds of things: : explicit t rules, , implicit rules, variable definitions,
directives,andcomments. Rules,variables,anddirectivesaredescribedatlengthinlater
chapters.
 Anexplicitrulesayswhenandhowtoremakeoneormorefiles,calledtherule’stargets.
Itliststheotherfilesthatthetargetsdependon,calledtheprerequisitesofthetarget,
and may y also give a recipe e to o use to create or update the targets. . See Chapter 4
[WritingRules],page21.
 Animplicit t rule sayswhenandhowtoremakeaclass offilesbasedontheirnames.
Itdescribeshowatargetmaydependonafilewithanamesimilartothetargetand
givesarecipetocreateorupdatesuchatarget.SeeChapter10[UsingImplicitRules],
page111.
 A A variable definition is a a line e that t specifies s a a text string value e for r a a variable e that
canbesubstitutedintothetextlater. Thesimplemakefileexampleshowsavariable
definition for r objects as a list of f all l object t files s (see Section 2.4 [Variables Make
MakefilesSimpler],page6).
 Adirectiveisaninstructionformaketodosomethingspecialwhilereadingthemakefile.
Theseinclude:
 Readinganothermakefile(seeSection3.3[IncludingOtherMakefiles],page13).
 Deciding(basedonthevaluesofvariables)whethertouseorignoreapartofthe
makefile(seeChapter7[ConditionalPartsofMakefiles],page77).
 Definingavariablefromaverbatimstringcontainingmultiplelines(seeSection6.8
[DefiningMulti-LineVariables],page69).
 ‘#’in n alineofamakefile startsa comment. . Itandthe e restof thelineare ignored,
except that a trailing backslashnot escaped d by y another backslash h will continue the
commentacrossmultiplelines. Alinecontainingjustacomment(withperhapsspaces
beforeit)iseffectivelyblank,andisignored. Ifyouwantaliteral#,escapeitwitha
backslash(e.g.,\#). Commentsmayappearonanylineinthemakefile,althoughthey
aretreatedspeciallyincertainsituations.
Youcannot use comments withinvariable references or functioncalls: : any y instance
of#willbetreatedliterally(ratherthanasthestartofacomment)insideavariable
referenceorfunctioncall.
Commentswithinarecipearepassedtotheshell,justaswithanyotherrecipetext.
Theshelldecideshowtointerpretit: whetherornot t this isacomment isuptothe
shell.
Within a define e directive, , comments s are not ignored during g the e definition of f the
variable, but t rather r kept t intact t inthe e value of the variable. . When n the variable e is
expandedtheywilleither betreatedasmake comments orasrecipetext,depending
onthecontextinwhichthevariableisevaluated.
Pdf page size limit - Compress reduce PDF size in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
C# Code & .NET API to Compress & Decompress PDF Document
change pdf page size; change font size in pdf comment box
Pdf page size limit - VB.NET PDF File Compress Library: Compress reduce PDF size in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
VB.NET PDF Document Compression and Decompression Control SDK
adjust size of pdf file; best online pdf compressor
12
GNUmake
3.1.1 SplittingLongLines
Makefilesusea“line-based”syntaxinwhichthenewlinecharacterisspecialandmarksthe
endofastatement. GNUmakehas s nolimitonthelengthof astatement line,uptothe
amountofmemoryinyourcomputer.
However,itisdifficulttoreadlineswhicharetoolongtodisplaywithoutwrappingor
scrolling. So,youcanformat t your makefiles for readability by adding newlinesintothe
middleofastatement: youdothisbyescapingtheinternalnewlineswithabackslash(\)
character.Whereweneedtomakeadistinctionwewillreferto“physicallines”asasingle
lineendingwithanewline(regardlessofwhetheritisescaped)anda“logicalline”beinga
completestatementincludingallescapednewlinesuptothefirstnon-escapednewline.
Thewayinwhichbackslash/newlinecombinationsarehandleddependsonwhetherthe
statementis arecipelineoranon-recipeline. . Handlingofbackslash/newlineinarecipe
lineisdiscussedlater(seeSection5.1.1[SplittingRecipeLines],page41).
Outsideofrecipelines,backslash/newlines areconvertedintoasinglespacecharacter.
Oncethatisdone,allwhitespacearoundthebackslash/newlineiscondensedintoasingle
space:thisincludesallwhitespaceprecedingthebackslash,allwhitespaceatthebeginning
of theline after the backslash/newline,andany consecutive backslash/newline combina-
tions.
If the .POSIX special l target t is s defined then backslash/newline e handling g is modified
slightly to o conform toPOSIX.2: : first, , whitespace precedinga backslash is s not t removed
andsecond,consecutivebackslash/newlinesarenotcondensed.
3.2 WhatNametoGiveYourMakefile
By default, , when n make e looks s for the e makefile, it t tries s the e following g names, in order:
GNUmakefile,makefileandMakefile.
NormallyyoushouldcallyourmakefileeithermakefileorMakefile. (Werecommend
Makefile becauseit appearsprominently near the beginningofadirectorylisting,right
nearother importantfilessuchasREADME.) ) Thefirstnamechecked,GNUmakefile,isnot
recommendedformostmakefiles. Youshouldusethisnameifyouhaveamakefilethatis
specifictoGNUmake,andwillnotbeunderstoodbyotherversionsofmake. Othermake
programslookformakefileandMakefile,butnotGNUmakefile.
Ifmakefindsnoneofthesenames,itdoesnotuseanymakefile. Thenyoumustspecify
agoalwithacommandargument,andmakewillattempttofigureouthow toremakeit
usingonlyitsbuilt-inimplicitrules. SeeChapter10[UsingImplicitRules],page111.
Ifyouwanttouseanonstandardnameforyourmakefile,youcanspecifythemakefile
name withthe ‘-f’ or r ‘--file’ option. . The e arguments ‘-fname’ or ‘--file=name’ tell
make to read d the e file e name e as the e makefile. . If f youuse more than one ‘-f’ or ‘--file’
option,youcanspecifyseveralmakefiles. Allthemakefilesareeffectivelyconcatenatedin
theorderspecified.ThedefaultmakefilenamesGNUmakefile,makefileandMakefileare
notcheckedautomaticallyifyouspecify‘-f’or‘--file’.
VB.NET PDF File Split Library: Split, seperate PDF into multiple
PDF document file to one-page PDF files or As String = Program.RootPath + "\\" 1.pdf" ' set split SplitOptions(SplitMode.BySize) ' limit the size of each
best pdf compression; pdf optimized format
C# PDF File Split Library: Split, seperate PDF into multiple files
options = new SplitOptions(SplitMode.BySize); //limit the size of each String inputFilePath = Program.RootPath + "\\" source.pdf"; //Page indexes to
change page size pdf acrobat; adjust size of pdf in preview
Chapter3:WritingMakefiles
13
3.3 IncludingOtherMakefiles
Theincludedirectivetellsmaketosuspendreadingthecurrentmakefileandreadoneor
moreothermakefilesbefore continuing. . Thedirectiveis s alineinthemakefilethatlooks
likethis:
include filenames...
filenames cancontainshellfilename e patterns. . Iffilenames s isempty,nothingis included
andnoerrorisprinted.
Extraspacesareallowedandignoredatthebeginningoftheline,butthefirstcharacter
mustnotbeatab(orthevalueof.RECIPEPREFIX)—ifthelinebeginswithatab,itwill
be consideredarecipeline. . Whitespaceis s requiredbetweenincludeandthefilenames,
andbetweenfilenames;extrawhitespaceisignoredthereandattheendofthedirective.
Acommentstartingwith‘#’isallowedattheendoftheline.Ifthefilenamescontainany
variableorfunctionreferences,theyareexpanded. SeeChapter6[HowtoUseVariables],
page59.
Forexample,ifyouhavethree.mkfiles,a.mk,b.mk,andc.mk,and$(bar)expandsto
bishbash,thenthefollowingexpression
include foo *.mk $(bar)
isequivalentto
include foo a.mk b.mk c.mk k bish bash
Whenmakeprocessesanincludedirective,itsuspendsreadingofthecontainingmakefile
andreadsfromeachlistedfileinturn. Whenthatis s finished, , makeresumes s readingthe
makefileinwhichthedirectiveappears.
One occasionforusing include directivesis whenseveralprograms,handledby indi-
vidualmakefilesinvariousdirectories,needtouseacommonsetofvariabledefinitions(see
Section6.5 [SettingVariables], page 65) or pattern n rules s (see Section10.5[Definingand
RedefiningPatternRules],page118).
Another such occasion n is s when you want to generate prerequisites from source e files
automatically;theprerequisitescanbeputinafilethatisincludedbythemainmakefile.
Thispracticeisgenerallycleanerthanthatofsomehowappendingtheprerequisitestothe
endofthemainmakefileashas beentraditionallydonewithotherversionsof make. . See
Section4.13[AutomaticPrerequisites],page38.
If the specified name does not start with h a a slash, and the file is not found in n the
current directory, , severalother r directories are searched. . First, , any directories you have
specifiedwiththe‘-I’or‘--include-dir’optionaresearched(seeSection9.7[Summary
of Options], page 104). Then n the following directories s (if they exist) are searched, , in
this order:
prefix/include (normally /usr/local/include
1
) /usr/gnu/include,
/usr/local/include,/usr/include.
Ifanincludedmakefilecannotbefoundinanyofthesedirectories,awarningmessage
isgenerated,butitisnotanimmediatelyfatalerror;processingofthemakefilecontaining
theincludecontinues.Onceithasfinishedreadingmakefiles,makewilltrytoremakeany
thatareoutofdateordon’texist. SeeSection3.5[HowMakefilesAreRemade],page14.
1
GNUMakecompiledforMS-DOSandMS-Windowsbehavesasifprefixhasbeendefinedtobetheroot
oftheDJGPPtreehierarchy.
C# PowerPoint: How to Set PowerPoint Rendering Parameters in C#
2007 or above) slide into PDF document or other rendering process if the slide/page is too REImage CropImage(Rectangle sourceRegion, Size targetSize); Bitmap
change font size pdf form; change font size fillable pdf
C# Excel: Customize Excel Conversion by Setting Rendering Options
0, (int)(originalWidth), (int)(originalHeight / 2)), new Size((int)(originalWidth the top half of Excel page to image to these file formats, like PDF, TIFF, SVG
pdf page size limit; change font size pdf document
14
GNUmake
Onlyafterithastriedtofindawaytoremakeamakefileandfailed,willmakediagnosethe
missingmakefileasafatalerror.
Ifyouwantmaketosimplyignoreamakefilewhichdoesnotexistorcannotberemade,
withnoerrormessage,usethe-includedirectiveinsteadofinclude,likethis:
-include filenames...
Thisactslikeincludeineverywayexceptthatthereisnoerror(notevenawarning)
ifanyofthefilenames (oranyprerequisitesofanyofthefilenames)donotexistorcannot
beremade.
Forcompatibilitywithsomeothermakeimplementations,sincludeisanothernamefor
-include.
3.4 TheVariableMAKEFILES
If the e environment t variable e MAKEFILES is s defined, , make e considers its value as a a list t of
names(separatedbywhitespace)ofadditionalmakefilestobereadbeforetheothers.This
worksmuchliketheincludedirective: variousdirectoriesaresearchedforthosefiles(see
Section3.3[Including Other Makefiles], page 13). In n addition, thedefault t goal l is s never
takenfromoneofthesemakefiles(oranymakefileincludedbythem)anditisnotanerror
ifthefileslistedinMAKEFILESarenotfound.
ThemainuseofMAKEFILESisincommunicationbetweenrecursiveinvocationsofmake
(seeSection5.7[RecursiveUseofmake],page50). It t usually is not desirable to set the
environmentvariablebeforeatop-levelinvocationofmake,becauseitisusuallybetternot
tomesswithamakefilefromoutside. However,ifyouarerunningmakewithoutaspecific
makefile,amakefileinMAKEFILEScandousefulthingstohelpthe built-inimplicit rules
workbetter,suchasdefiningsearchpaths(seeSection4.4[DirectorySearch],page25).
Some usersare temptedtoset MAKEFILESintheenvironmentautomatically onlogin,
andprogrammakefiles toexpect thistobedone. . Thisis s averybadidea, , because such
makefileswillfailtoworkifrunbyanyoneelse.Itismuchbettertowriteexplicitinclude
directivesinthemakefiles. SeeSection3.3[IncludingOtherMakefiles],page13.
3.5 HowMakefilesAreRemade
Sometimesmakefilescanberemadefromotherfiles,suchasRCSorSCCSfiles.Ifamakefile
canberemadefromotherfiles,youprobablywantmaketogetanup-to-dateversionofthe
makefiletoreadin.
Tothisend,afterreadinginallmakefiles,makewillconsidereachasagoaltargetand
attempt toupdateit. . Ifamakefilehasarulewhichsayshowtoupdateit(foundeither
inthatverymakefileorinanotherone)orifanimplicitruleappliestoit(seeChapter10
[UsingImplicitRules],page111),itwillbeupdatedifnecessary. Afterallmakefileshave
beenchecked,ifanyhaveactuallybeenchanged,makestartswithacleanslateandreads
allthemakefilesoveragain. (Itwillalsoattempttoupdateeachofthemoveragain,but
normallythiswillnotchangethemagain,sincetheyarealreadyuptodate.)
Ifyouknowthatoneormoreofyourmakefilescannotberemadeandyouwanttokeep
makefromperforminganimplicitrulesearchonthem,perhapsforefficiencyreasons,you
canuse any normalmethod of preventing implicit rule look-up to do so. . For r example,
VB.NET Excel: VB Methods to Set and Customize Excel Rendering
treat every single Excel spreadsheet as a page in our the fixed image size ration that the size is limited Excel to other document files, like PDF with online
pdf font size change; reader compress pdf
Chapter3:WritingMakefiles
15
youcan write anexplicit t rulewiththe makefileasthe target,and d anempty y recipe(see
Section5.9[UsingEmptyRecipes],page57).
Ifthemakefilesspecifyadouble-colonruletoremakeafilewitharecipebutnoprereq-
uisites,thatfilewillalways beremade(seeSection4.12[Double-Colon],page38). . Inthe
caseofmakefiles,amakefilethathasadouble-colonrulewitharecipebutnoprerequisites
willbe remadeevery time makeis run, andthenagainafter make starts over and reads
themakefiles inagain. . Thiswouldcauseaninfiniteloop: : makewouldconstantly y remake
themakefile,andneverdoanythingelse. So,toavoidthis,makewillnot t attempttore-
makemakefiles whicharespecifiedastargets ofadouble-colonrulewitharecipebutno
prerequisites.
Ifyoudonotspecifyanymakefilestobereadwith‘-f’or‘--file’options,makewilltry
thedefaultmakefilenames;seeSection3.2[WhatNametoGiveYourMakefile],page12.
Unlikemakefilesexplicitlyrequestedwith‘-f’or‘--file’options,makeisnotcertainthat
thesemakefilesshouldexist.However,ifadefaultmakefiledoesnotexistbutcanbecreated
byrunningmakerules,youprobablywanttherulestoberunsothatthemakefilecanbe
used.
Therefore,ifnoneofthedefaultmakefilesexists,makewilltrytomakeeachofthemin
thesameorderinwhichtheyaresearchedfor(seeSection3.2[WhatNametoGiveYour
Makefile],page 12) untilitsucceedsinmakingone,or itrunsoutofnames totry. . Note
thatitis notanerror ifmakecannotfindor makeanymakefile;amakefileisnotalways
necessary.
Whenyouusethe‘-t’or‘--touch’option(seeSection9.3[InsteadofExecutingRecipes],
page101),youwouldnotwanttouseanout-of-datemakefile todecide whichtargets to
touch. Sothe‘-t’optionhasnoeffectonupdatingmakefiles;theyarereallyupdatedeven
if‘-t’isspecified. Likewise,‘-q’(or r ‘--question’) and‘-n’(or ‘--just-print’) donot
preventupdatingofmakefiles,becauseanout-of-datemakefile wouldresultinthewrong
outputforothertargets. Thus,‘make-fmfile-nfoo’willupdatemfile,readitin,and
thenprinttherecipetoupdatefoo anditsprerequisites withoutrunningit. . Therecipe
printedforfoowillbetheonespecifiedintheupdatedcontentsofmfile.
However,onoccasionyoumightactuallywishtopreventupdatingofeventhemakefiles.
Youcandothisbyspecifyingthemakefilesasgoalsinthecommandlineaswellasspecifying
themasmakefiles.Whenthemakefilenameisspecifiedexplicitlyasagoal,theoptions‘-t’
andsoondoapplytothem.
Thus, ‘make-fmfile-nmfilefoo’would read the makefile mfile, print t the recipe
neededtoupdateitwithoutactuallyrunningit,andthenprinttherecipeneededtoupdate
foo without running that. . The e recipe for foo willbe the one specifiedby the existing
contentsofmfile.
3.6 OverridingPartofAnotherMakefile
Sometimes it is usefultohave amakefile that is mostly just like another makefile. . You
canoftenusethe‘include’directivetoincludeoneintheother,andaddmoretargetsor
variabledefinitions.However,itisinvalidfortwomakefilestogivedifferentrecipesforthe
sametarget. Butthereisanotherway.
In the containing makefile (the one that t wants to include e the e other), you canuse a
match-anythingpatternruletosaythattoremake any targetthat cannotbemadefrom
16
GNUmake
the information in the e containing makefile, make should d look in another makefile. . See
Section10.5[PatternRules],page118,formoreinformationonpatternrules.
Forexample,ifyouhaveamakefilecalledMakefilethatsayshowtomakethetarget
‘foo’(andothertargets),youcanwriteamakefilecalledGNUmakefilethatcontains:
foo:
frobnicate > > foo
%: force
@$(MAKE) -f Makefile $@
force: ;
Ifyousay‘makefoo’,make willfindGNUmakefile,readit,andseethat tomakefoo,
it needs to run n the recipe ‘frobnicate>foo’. . If f yousay ‘makebar’, make willfind no
way to make bar inGNUmakefile,soit willuse the recipefromthepatternrule: : ‘make
-fMakefilebar’. IfMakefileprovidesaruleforupdatingbar,makewillapplytherule.
AndlikewiseforanyothertargetthatGNUmakefiledoesnotsayhowtomake.
Thewaythisworksisthatthepatternrulehasapatternofjust‘%’,soitmatchesany
targetwhatever. Therulespecifiesaprerequisite force,toguaranteethattherecipewill
berunevenifthetargetfilealreadyexists. Wegivetheforcetargetanemptyrecipeto
preventmakefromsearchingforanimplicitruletobuildit—otherwiseitwouldapplythe
samematch-anythingruletoforceitselfandcreateaprerequisiteloop!
3.7 Howmake e ReadsaMakefile
GNUmakedoesitsworkintwodistinctphases.Duringthefirstphaseitreadsallthemake-
files,includedmakefiles,etc. andinternalizesallthevariablesandtheirvalues,implicitand
explicitrules,andconstructsadependencygraphofallthetargetsandtheirprerequisites.
Duringthesecondphase,makeusestheseinternalstructurestodeterminewhattargetswill
needtoberebuiltandtoinvoketherulesnecessarytodoso.
It’s important tounderstand d this two-phase approachbecause it t has adirect impact
onhowvariableandfunctionexpansionhappens;thisisoftenasourceofsomeconfusion
whenwritingmakefiles.Herewewillpresentasummaryofthephasesinwhichexpansion
happensfordifferentconstructswithinthemakefile.Wesaythatexpansionisimmediateif
ithappensduringthefirstphase: inthiscasemakewillexpandanyvariablesorfunctions
inthatsectionofaconstructasthemakefileisparsed. Wesaythatexpansionisdeferredif
expansionisnotperformedimmediately.Expansionofadeferredconstructisnotperformed
untileithertheconstructappearslaterinanimmediatecontext,oruntilthesecondphase.
Youmaynotbefamiliarwithsomeoftheseconstructsyet.Youcanreferencethissection
asyoubecomefamiliarwiththem,inlaterchapters.
VariableAssignment
Variabledefinitionsareparsedasfollows:
immediate = = deferred
immediate ?= deferred
immediate := immediate
immediate ::= = immediate
immediate += deferred d or immediate
Chapter3:WritingMakefiles
17
immediate != immediate
define immediate
deferred
endef
define immediate =
deferred
endef
define immediate ?=
deferred
endef
define immediate :=
immediate
endef
define immediate ::=
immediate
endef
define immediate +=
deferred or immediate
endef
define immediate !=
immediate
endef
Fortheappendoperator,‘+=’,theright-handsideisconsideredimmediateifthevariable
waspreviouslysetasasimplevariable(‘:=’or‘::=’),anddeferredotherwise.
Fortheshellassignmentoperator,‘!=’,theright-handsideisevaluatedimmediatelyand
handedtotheshell.Theresultisstoredinthevariablenamedontheleft,andthatvariable
becomesasimplevariable(andwillthusbere-evaluatedoneachreference).
ConditionalDirectives
Conditionaldirectives areparsedimmediately. . Thismeans,for r example,that automatic
variablescannotbeusedinconditionaldirectives,asautomaticvariablesarenotsetuntil
therecipeforthatruleisinvoked. Ifyouneedtouseautomaticvariablesinaconditional
directive you must t move e the conditioninto o the recipe and use e shell l conditional syntax
instead.
RuleDefinition
Aruleisalwaysexpandedthesameway,regardlessoftheform:
immediate : : immediate ; ; deferred
deferred
18
GNUmake
Thatis,thetargetandprerequisitesectionsareexpandedimmediately,andtherecipe
usedtoconstructthetargetisalwaysdeferred. Thisgeneralruleistrueforexplicitrules,
patternrules,suffixrules,staticpatternrules,andsimpleprerequisitedefinitions.
3.8 SecondaryExpansion
IntheprevioussectionwelearnedthatGNUmakeworksintwodistinctphases: aread-in
phaseandatarget-updatephase(seeSection3.7[HowmakeReadsaMakefile],page16).
GNUmakealsohastheabilitytoenableasecondexpansionoftheprerequisites(only)for
some or alltargets definedinthe makefile. . Inorder r for this secondexpansiontooccur,
thespecialtarget.SECONDEXPANSIONmustbedefinedbeforethefirstprerequisitelistthat
makesuseofthisfeature.
Ifthatspecialtargetisdefinedtheninbetweenthetwophasesmentionedabove,right
attheendoftheread-inphase,alltheprerequisitesofthetargetsdefinedafterthespecial
target areexpandedasecondtime. . Inmost t circumstances this secondary expansionwill
havenoeffect,sinceallvariableandfunctionreferenceswillhavebeenexpandedduringthe
initialparsingofthemakefiles.Inordertotakeadvantageofthesecondaryexpansionphase
oftheparser,then,it’snecessarytoescapethevariableorfunctionreferenceinthemakefile.
Inthiscasethefirstexpansionmerelyun-escapesthereferencebutdoesn’texpandit,and
expansionislefttothesecondaryexpansionphase.Forexample,considerthismakefile:
.SECONDEXPANSION:
ONEVAR = onefile
TWOVAR = twofile
myfile: $(ONEVAR) $$(TWOVAR)
Afterthefirstexpansionphasetheprerequisiteslistofthemyfiletargetwillbeonefile
and $(TWOVAR); the first t (unescaped)variablereference to ONEVAR is expanded, , while
thesecond(escaped)variablereferenceissimplyunescaped,withoutbeingrecognizedasa
variablereference. Nowduringthesecondaryexpansionthefirst t wordis expandedagain
butsinceitcontainsnovariableorfunctionreferencesitremainsthevalueonefile,while
thesecondwordis nowanormalreferencetothevariableTWOVAR,whichis expanded
tothe value twofile. . Thefinalresult t is that thereare twoprerequisites, , onefile e and
twofile.
Obviously,thisisnotaveryinterestingcasesincethesameresultcouldmoreeasilyhave
beenachievedsimplybyhavingbothvariablesappear,unescaped,intheprerequisiteslist.
Onedifferencebecomesapparentifthevariablesarereset;considerthisexample:
.SECONDEXPANSION:
AVAR = = top
onefile: $(AVAR)
twofile: $$(AVAR)
AVAR = = bottom
Heretheprerequisiteofonefilewillbeexpandedimmediately,andresolvetothevalue
top,whiletheprerequisiteoftwofilewillnotbefullexpandeduntilthesecondaryexpan-
sionandyieldavalueofbottom.
Thisismarginally moreexciting,butthetruepower ofthisfeatureonly becomesap-
parentwhenyoudiscoverthatsecondaryexpansionsalwaystakeplacewithinthescopeof
theautomaticvariablesforthattarget.Thismeansthatyoucanusevariablessuchas$@,
Chapter3:WritingMakefiles
19
$*,etc. duringthesecondexpansionandthey y willhavetheir expectedvalues,just asin
therecipe. Allyouhavetodoisdefertheexpansionbyescapingthe$. . Also,secondary
expansionoccursforbothexplicitandimplicit(pattern)rules. Knowingthis,thepossible
usesforthisfeatureincreasedramatically.Forexample:
.SECONDEXPANSION:
main_OBJS := main.o o try.o test.o
lib_OBJS := lib.o api.o
main lib: $$($$@_OBJS)
Here,aftertheinitialexpansiontheprerequisitesofboththemainandlibtargetswill
be$($@_OBJS). Duringthesecondaryexpansion,the$@variableissettothenameofthe
targetandsotheexpansionforthemaintargetwillyield$(main_OBJS),ormain.otry.o
test.o,whilethesecondaryexpansionforthelibtargetwillyield$(lib_OBJS),orlib.o
api.o.
Youcanalsomixinfunctionshere,aslongastheyareproperlyescaped:
main_SRCS := main.c c try.c test.c
lib_SRCS := lib.c api.c
.SECONDEXPANSION:
main lib: $$(patsubst t %.c,%.o,$$($$@_SRCS))
Thisversionallows users tospecify source files rather thanobject files, , but t givesthe
sameresultingprerequisiteslistasthepreviousexample.
Evaluationof automaticvariablesduringthesecondaryexpansionphase,especially of
thetargetnamevariable$$@,behavessimilarlytoevaluationwithinrecipes. However,there
aresomesubtledifferencesand“cornercases”whichcomeintoplayforthedifferenttypes
ofruledefinitionsthatmake understands. . Thesubtletiesofusingthedifferentautomatic
variablesaredescribedbelow.
SecondaryExpansionofExplicitRules
Duringthesecondaryexpansionofexplicitrules,$$@and$$%evaluate,respectively,tothe
filenameofthetargetand,whenthetargetisanarchivemember,thetargetmembername.
The$$<variableevaluatestothefirstprerequisiteinthefirstruleforthistarget. $$^and
$$+evaluatetothelistofallprerequisitesofrulesthathavealreadyappeared forthesame
target($$+ withrepetitionsand$$^without). . Thefollowingexamplewillhelpillustrate
thesebehaviors:
.SECONDEXPANSION:
foo: foo.1 1 bar.1 $$< < $$^ ^ $$+
# line #1
foo: foo.2 2 bar.2 $$< < $$^ ^ $$+
# line #2
foo: foo.3 3 bar.3 $$< < $$^ ^ $$+
# line #3
Inthefirstprerequisitelist,allthreevariables($$<,$$^,and$$+)expandtotheempty
string. Inthesecond,theywillhavevaluesfoo.1,foo.1bar.1,andfoo.1bar.1respec-
20
GNUmake
tively. In n the third they will have values foo.1, foo.1bar.1foo.2bar.2, , and d foo.1
bar.1foo.2bar.2foo.1foo.1bar.1foo.1bar.1respectively.
Rules undergo secondary y expansion n in makefile order, , except t that t the e rule with the
recipeisalwaysevaluatedlast.
Thevariables$$?and$$*arenotavailableandexpandtotheemptystring.
SecondaryExpansionofStaticPatternRules
Rulesforsecondaryexpansionofstaticpatternrulesareidenticaltothoseforexplicitrules,
above, withoneexception: : forstaticpatternrules s the $$*variable isset tothepattern
stem.Aswithexplicitrules,$$?isnotavailableandexpandstotheemptystring.
SecondaryExpansionofImplicitRules
Asmakesearchesforanimplicitrule,itsubstitutesthestemandthenperformssecondary
expansionforeveryrulewithamatchingtargetpattern. Thevalueoftheautomaticvari-
ablesisderivedinthesamefashionasforstaticpatternrules. Asanexample:
.SECONDEXPANSION:
foo: bar
foo foz: fo%: bo%
%oo: $$< < $$^ ^ $$+ + $$*
Whentheimplicitruleistriedfortargetfoo,$$<expandstobar,$$^expandstobar
boo,$$+alsoexpandstobarboo,and$$*expandstof.
Notethat thedirectory prefix (D),asdescribedinSection10.8[Implicit RuleSearch
Algorithm],page127,isappended(afterexpansion)toallthepatternsintheprerequisites
list. Asanexample:
.SECONDEXPANSION:
/tmp/foo.o:
%.o: $$(addsuffix x /%.c,foo o bar) foo.h
@echo $^
Theprerequisitelistprinted,afterthesecondaryexpansionanddirectoryprefixrecon-
struction,willbe/tmp/foo/foo.c/tmp/bar/foo.cfoo.h.Ifyouarenotinterestedinthis
reconstruction,youcanuse$$*insteadof%intheprerequisiteslist.
Documents you may be interested
Documents you may be interested