cmLocalGenerator.cxx 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmLocalGenerator.h"
  4. #include "cmAlgorithms.h"
  5. #include "cmComputeLinkInformation.h"
  6. #include "cmCustomCommand.h"
  7. #include "cmCustomCommandGenerator.h"
  8. #include "cmCustomCommandLines.h"
  9. #include "cmGeneratedFileStream.h"
  10. #include "cmGeneratorExpression.h"
  11. #include "cmGeneratorExpressionEvaluationFile.h"
  12. #include "cmGeneratorTarget.h"
  13. #include "cmGlobalGenerator.h"
  14. #include "cmInstallGenerator.h"
  15. #include "cmInstallScriptGenerator.h"
  16. #include "cmInstallTargetGenerator.h"
  17. #include "cmLinkLineComputer.h"
  18. #include "cmLinkLineDeviceComputer.h"
  19. #include "cmMakefile.h"
  20. #include "cmRulePlaceholderExpander.h"
  21. #include "cmSourceFile.h"
  22. #include "cmSourceFileLocation.h"
  23. #include "cmSourceFileLocationKind.h"
  24. #include "cmState.h"
  25. #include "cmStateDirectory.h"
  26. #include "cmStateTypes.h"
  27. #include "cmStringAlgorithms.h"
  28. #include "cmSystemTools.h"
  29. #include "cmTarget.h"
  30. #include "cmTestGenerator.h"
  31. #include "cmVersion.h"
  32. #include "cmake.h"
  33. #include "cmsys/RegularExpression.hxx"
  34. #if !defined(CMAKE_BOOTSTRAP)
  35. # define CM_LG_ENCODE_OBJECT_NAMES
  36. # include "cmCryptoHash.h"
  37. #endif
  38. #include <cm/string_view>
  39. #include <algorithm>
  40. #include <cassert>
  41. #include <cstdio>
  42. #include <cstdlib>
  43. #include <cstring>
  44. #include <functional>
  45. #include <initializer_list>
  46. #include <iterator>
  47. #include <sstream>
  48. #include <unordered_set>
  49. #include <utility>
  50. #include <vector>
  51. #if defined(__HAIKU__)
  52. # include <FindDirectory.h>
  53. # include <StorageDefs.h>
  54. #endif
  55. // List of variables that are replaced when
  56. // rules are expanced. These variables are
  57. // replaced in the form <var> with GetSafeDefinition(var).
  58. // ${LANG} is replaced in the variable first with all enabled
  59. // languages.
  60. static auto ruleReplaceVars = { "CMAKE_${LANG}_COMPILER",
  61. "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
  62. "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
  63. "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
  64. "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
  65. "CMAKE_${LANG}_LINK_FLAGS",
  66. "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
  67. "CMAKE_${LANG}_ARCHIVE",
  68. "CMAKE_AR",
  69. "CMAKE_CURRENT_SOURCE_DIR",
  70. "CMAKE_CURRENT_BINARY_DIR",
  71. "CMAKE_RANLIB",
  72. "CMAKE_LINKER",
  73. "CMAKE_MT",
  74. "CMAKE_CUDA_HOST_COMPILER",
  75. "CMAKE_CUDA_HOST_LINK_LAUNCHER",
  76. "CMAKE_CL_SHOWINCLUDES_PREFIX" };
  77. cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
  78. : cmOutputConverter(makefile->GetStateSnapshot())
  79. , StateSnapshot(makefile->GetStateSnapshot())
  80. , DirectoryBacktrace(makefile->GetBacktrace())
  81. {
  82. this->GlobalGenerator = gg;
  83. this->Makefile = makefile;
  84. this->AliasTargets = makefile->GetAliasTargets();
  85. this->EmitUniversalBinaryFlags = true;
  86. this->BackwardsCompatibility = 0;
  87. this->BackwardsCompatibilityFinal = false;
  88. this->ComputeObjectMaxPath();
  89. // Canonicalize entries of the CPATH environment variable the same
  90. // way detection of CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES does.
  91. {
  92. std::vector<std::string> cpath;
  93. cmSystemTools::GetPath(cpath, "CPATH");
  94. for (std::string& cp : cpath) {
  95. if (cmSystemTools::FileIsFullPath(cp)) {
  96. cp = cmSystemTools::CollapseFullPath(cp);
  97. this->EnvCPATH.emplace(std::move(cp));
  98. }
  99. }
  100. }
  101. std::vector<std::string> enabledLanguages =
  102. this->GetState()->GetEnabledLanguages();
  103. if (const char* sysrootCompile =
  104. this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
  105. this->CompilerSysroot = sysrootCompile;
  106. } else {
  107. this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  108. }
  109. if (const char* sysrootLink =
  110. this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
  111. this->LinkerSysroot = sysrootLink;
  112. } else {
  113. this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  114. }
  115. for (std::string const& lang : enabledLanguages) {
  116. if (lang == "NONE") {
  117. continue;
  118. }
  119. this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
  120. this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
  121. this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
  122. std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
  123. std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
  124. std::string const& compilerOptionTarget =
  125. "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
  126. std::string const& compilerExternalToolchain =
  127. "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
  128. std::string const& compilerOptionExternalToolchain =
  129. "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
  130. std::string const& compilerOptionSysroot =
  131. "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
  132. this->VariableMappings[compilerArg1] =
  133. this->Makefile->GetSafeDefinition(compilerArg1);
  134. this->VariableMappings[compilerTarget] =
  135. this->Makefile->GetSafeDefinition(compilerTarget);
  136. this->VariableMappings[compilerOptionTarget] =
  137. this->Makefile->GetSafeDefinition(compilerOptionTarget);
  138. this->VariableMappings[compilerExternalToolchain] =
  139. this->Makefile->GetSafeDefinition(compilerExternalToolchain);
  140. this->VariableMappings[compilerOptionExternalToolchain] =
  141. this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
  142. this->VariableMappings[compilerOptionSysroot] =
  143. this->Makefile->GetSafeDefinition(compilerOptionSysroot);
  144. for (std::string replaceVar : ruleReplaceVars) {
  145. if (replaceVar.find("${LANG}") != std::string::npos) {
  146. cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
  147. }
  148. this->VariableMappings[replaceVar] =
  149. this->Makefile->GetSafeDefinition(replaceVar);
  150. }
  151. }
  152. }
  153. cmRulePlaceholderExpander* cmLocalGenerator::CreateRulePlaceholderExpander()
  154. const
  155. {
  156. return new cmRulePlaceholderExpander(this->Compilers, this->VariableMappings,
  157. this->CompilerSysroot,
  158. this->LinkerSysroot);
  159. }
  160. cmLocalGenerator::~cmLocalGenerator()
  161. {
  162. cmDeleteAll(this->GeneratorTargets);
  163. cmDeleteAll(this->OwnedImportedGeneratorTargets);
  164. }
  165. void cmLocalGenerator::IssueMessage(MessageType t,
  166. std::string const& text) const
  167. {
  168. this->GetCMakeInstance()->IssueMessage(t, text, this->DirectoryBacktrace);
  169. }
  170. void cmLocalGenerator::ComputeObjectMaxPath()
  171. {
  172. // Choose a maximum object file name length.
  173. #if defined(_WIN32) || defined(__CYGWIN__)
  174. this->ObjectPathMax = 250;
  175. #else
  176. this->ObjectPathMax = 1000;
  177. #endif
  178. const char* plen = this->Makefile->GetDefinition("CMAKE_OBJECT_PATH_MAX");
  179. if (plen && *plen) {
  180. unsigned int pmax;
  181. if (sscanf(plen, "%u", &pmax) == 1) {
  182. if (pmax >= 128) {
  183. this->ObjectPathMax = pmax;
  184. } else {
  185. std::ostringstream w;
  186. w << "CMAKE_OBJECT_PATH_MAX is set to " << pmax
  187. << ", which is less than the minimum of 128. "
  188. << "The value will be ignored.";
  189. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  190. }
  191. } else {
  192. std::ostringstream w;
  193. w << "CMAKE_OBJECT_PATH_MAX is set to \"" << plen
  194. << "\", which fails to parse as a positive integer. "
  195. << "The value will be ignored.";
  196. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  197. }
  198. }
  199. this->ObjectMaxPathViolations.clear();
  200. }
  201. static void MoveSystemIncludesToEnd(std::vector<std::string>& includeDirs,
  202. const std::string& config,
  203. const std::string& lang,
  204. const cmGeneratorTarget* target)
  205. {
  206. if (!target) {
  207. return;
  208. }
  209. std::stable_sort(
  210. includeDirs.begin(), includeDirs.end(),
  211. [&target, &config, &lang](std::string const& a, std::string const& b) {
  212. return !target->IsSystemIncludeDirectory(a, config, lang) &&
  213. target->IsSystemIncludeDirectory(b, config, lang);
  214. });
  215. }
  216. static void MoveSystemIncludesToEnd(std::vector<BT<std::string>>& includeDirs,
  217. const std::string& config,
  218. const std::string& lang,
  219. const cmGeneratorTarget* target)
  220. {
  221. if (!target) {
  222. return;
  223. }
  224. std::stable_sort(includeDirs.begin(), includeDirs.end(),
  225. [target, &config, &lang](BT<std::string> const& a,
  226. BT<std::string> const& b) {
  227. return !target->IsSystemIncludeDirectory(a.Value, config,
  228. lang) &&
  229. target->IsSystemIncludeDirectory(b.Value, config, lang);
  230. });
  231. }
  232. void cmLocalGenerator::TraceDependencies()
  233. {
  234. std::vector<std::string> const& configs =
  235. this->Makefile->GetGeneratorConfigs();
  236. for (std::string const& c : configs) {
  237. this->GlobalGenerator->CreateEvaluationSourceFiles(c);
  238. }
  239. // Generate the rule files for each target.
  240. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  241. for (cmGeneratorTarget* target : targets) {
  242. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  243. continue;
  244. }
  245. target->TraceDependencies();
  246. }
  247. }
  248. void cmLocalGenerator::GenerateTestFiles()
  249. {
  250. if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
  251. return;
  252. }
  253. // Compute the set of configurations.
  254. std::vector<std::string> configurationTypes;
  255. const std::string& config =
  256. this->Makefile->GetConfigurations(configurationTypes, false);
  257. std::string file =
  258. cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentBinary(),
  259. "/CTestTestfile.cmake");
  260. cmGeneratedFileStream fout(file);
  261. fout.SetCopyIfDifferent(true);
  262. fout << "# CMake generated Testfile for " << std::endl
  263. << "# Source directory: "
  264. << this->StateSnapshot.GetDirectory().GetCurrentSource() << std::endl
  265. << "# Build directory: "
  266. << this->StateSnapshot.GetDirectory().GetCurrentBinary() << std::endl
  267. << "# " << std::endl
  268. << "# This file includes the relevant testing commands "
  269. << "required for " << std::endl
  270. << "# testing this directory and lists subdirectories to "
  271. << "be tested as well." << std::endl;
  272. const char* testIncludeFile =
  273. this->Makefile->GetProperty("TEST_INCLUDE_FILE");
  274. if (testIncludeFile) {
  275. fout << "include(\"" << testIncludeFile << "\")" << std::endl;
  276. }
  277. const char* testIncludeFiles =
  278. this->Makefile->GetProperty("TEST_INCLUDE_FILES");
  279. if (testIncludeFiles) {
  280. std::vector<std::string> includesList = cmExpandedList(testIncludeFiles);
  281. for (std::string const& i : includesList) {
  282. fout << "include(\"" << i << "\")" << std::endl;
  283. }
  284. }
  285. // Ask each test generator to write its code.
  286. std::vector<cmTestGenerator*> const& testers =
  287. this->Makefile->GetTestGenerators();
  288. for (cmTestGenerator* tester : testers) {
  289. tester->Compute(this);
  290. tester->Generate(fout, config, configurationTypes);
  291. }
  292. using vec_t = std::vector<cmStateSnapshot>;
  293. vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
  294. std::string parentBinDir = this->GetCurrentBinaryDirectory();
  295. for (cmStateSnapshot const& i : children) {
  296. // TODO: Use add_subdirectory instead?
  297. std::string outP = i.GetDirectory().GetCurrentBinary();
  298. outP = this->MaybeConvertToRelativePath(parentBinDir, outP);
  299. outP = cmOutputConverter::EscapeForCMake(outP);
  300. fout << "subdirs(" << outP << ")" << std::endl;
  301. }
  302. // Add directory labels property
  303. const char* directoryLabels =
  304. this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
  305. const char* labels = this->Makefile->GetProperty("LABELS");
  306. if (labels || directoryLabels) {
  307. fout << "set_directory_properties(PROPERTIES LABELS ";
  308. if (labels) {
  309. fout << cmOutputConverter::EscapeForCMake(labels);
  310. }
  311. if (labels && directoryLabels) {
  312. fout << ";";
  313. }
  314. if (directoryLabels) {
  315. fout << cmOutputConverter::EscapeForCMake(directoryLabels);
  316. }
  317. fout << ")" << std::endl;
  318. }
  319. }
  320. void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
  321. {
  322. std::vector<cmGeneratorExpressionEvaluationFile*> ef =
  323. this->Makefile->GetEvaluationFiles();
  324. for (cmGeneratorExpressionEvaluationFile* geef : ef) {
  325. geef->CreateOutputFile(this, config);
  326. }
  327. }
  328. void cmLocalGenerator::ProcessEvaluationFiles(
  329. std::vector<std::string>& generatedFiles)
  330. {
  331. for (cmGeneratorExpressionEvaluationFile* geef :
  332. this->Makefile->GetEvaluationFiles()) {
  333. geef->Generate(this);
  334. if (cmSystemTools::GetFatalErrorOccured()) {
  335. return;
  336. }
  337. std::vector<std::string> files = geef->GetFiles();
  338. std::sort(files.begin(), files.end());
  339. std::vector<std::string> intersection;
  340. std::set_intersection(files.begin(), files.end(), generatedFiles.begin(),
  341. generatedFiles.end(),
  342. std::back_inserter(intersection));
  343. if (!intersection.empty()) {
  344. cmSystemTools::Error("Files to be generated by multiple different "
  345. "commands: " +
  346. cmWrap('"', intersection, '"', " "));
  347. return;
  348. }
  349. cmAppend(generatedFiles, files);
  350. std::inplace_merge(generatedFiles.begin(),
  351. generatedFiles.end() - files.size(),
  352. generatedFiles.end());
  353. }
  354. }
  355. void cmLocalGenerator::GenerateInstallRules()
  356. {
  357. // Compute the install prefix.
  358. const char* prefix = this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
  359. #if defined(_WIN32) && !defined(__CYGWIN__)
  360. std::string prefix_win32;
  361. if (!prefix) {
  362. if (!cmSystemTools::GetEnv("SystemDrive", prefix_win32)) {
  363. prefix_win32 = "C:";
  364. }
  365. const char* project_name = this->Makefile->GetDefinition("PROJECT_NAME");
  366. if (project_name && project_name[0]) {
  367. prefix_win32 += "/Program Files/";
  368. prefix_win32 += project_name;
  369. } else {
  370. prefix_win32 += "/InstalledCMakeProject";
  371. }
  372. prefix = prefix_win32.c_str();
  373. }
  374. #elif defined(__HAIKU__)
  375. char dir[B_PATH_NAME_LENGTH];
  376. if (!prefix) {
  377. if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  378. B_OK) {
  379. prefix = dir;
  380. } else {
  381. prefix = "/boot/system";
  382. }
  383. }
  384. #else
  385. if (!prefix) {
  386. prefix = "/usr/local";
  387. }
  388. #endif
  389. if (const char* stagingPrefix =
  390. this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
  391. prefix = stagingPrefix;
  392. }
  393. // Compute the set of configurations.
  394. std::vector<std::string> configurationTypes;
  395. const std::string& config =
  396. this->Makefile->GetConfigurations(configurationTypes, false);
  397. // Choose a default install configuration.
  398. std::string default_config = config;
  399. const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
  400. "DEBUG", nullptr };
  401. for (const char** c = default_order; *c && default_config.empty(); ++c) {
  402. for (std::string const& configurationType : configurationTypes) {
  403. if (cmSystemTools::UpperCase(configurationType) == *c) {
  404. default_config = configurationType;
  405. }
  406. }
  407. }
  408. if (default_config.empty() && !configurationTypes.empty()) {
  409. default_config = configurationTypes[0];
  410. }
  411. // Create the install script file.
  412. std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  413. std::string homedir = this->GetState()->GetBinaryDirectory();
  414. int toplevel_install = 0;
  415. if (file == homedir) {
  416. toplevel_install = 1;
  417. }
  418. file += "/cmake_install.cmake";
  419. cmGeneratedFileStream fout(file);
  420. fout.SetCopyIfDifferent(true);
  421. // Write the header.
  422. fout << "# Install script for directory: "
  423. << this->StateSnapshot.GetDirectory().GetCurrentSource() << std::endl
  424. << std::endl;
  425. fout << "# Set the install prefix" << std::endl
  426. << "if(NOT DEFINED CMAKE_INSTALL_PREFIX)" << std::endl
  427. << " set(CMAKE_INSTALL_PREFIX \"" << prefix << "\")" << std::endl
  428. << "endif()" << std::endl
  429. << R"(string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX )"
  430. << "\"${CMAKE_INSTALL_PREFIX}\")" << std::endl
  431. << std::endl;
  432. // Write support code for generating per-configuration install rules.
  433. /* clang-format off */
  434. fout <<
  435. "# Set the install configuration name.\n"
  436. "if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
  437. " if(BUILD_TYPE)\n"
  438. " string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
  439. " CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
  440. " else()\n"
  441. " set(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
  442. " endif()\n"
  443. " message(STATUS \"Install configuration: "
  444. "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
  445. "endif()\n"
  446. "\n";
  447. /* clang-format on */
  448. // Write support code for dealing with component-specific installs.
  449. /* clang-format off */
  450. fout <<
  451. "# Set the component getting installed.\n"
  452. "if(NOT CMAKE_INSTALL_COMPONENT)\n"
  453. " if(COMPONENT)\n"
  454. " message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
  455. " set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
  456. " else()\n"
  457. " set(CMAKE_INSTALL_COMPONENT)\n"
  458. " endif()\n"
  459. "endif()\n"
  460. "\n";
  461. /* clang-format on */
  462. // Copy user-specified install options to the install code.
  463. if (const char* so_no_exe =
  464. this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE")) {
  465. /* clang-format off */
  466. fout <<
  467. "# Install shared libraries without execute permission?\n"
  468. "if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
  469. " set(CMAKE_INSTALL_SO_NO_EXE \"" << so_no_exe << "\")\n"
  470. "endif()\n"
  471. "\n";
  472. /* clang-format on */
  473. }
  474. // Copy cmake cross compile state to install code.
  475. if (const char* crosscompiling =
  476. this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
  477. /* clang-format off */
  478. fout <<
  479. "# Is this installation the result of a crosscompile?\n"
  480. "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
  481. " set(CMAKE_CROSSCOMPILING \"" << crosscompiling << "\")\n"
  482. "endif()\n"
  483. "\n";
  484. /* clang-format on */
  485. }
  486. // Write default directory permissions.
  487. if (const char* defaultDirPermissions = this->Makefile->GetDefinition(
  488. "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS")) {
  489. /* clang-format off */
  490. fout <<
  491. "# Set default install directory permissions.\n"
  492. "if(NOT DEFINED CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS)\n"
  493. " set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS \""
  494. << defaultDirPermissions << "\")\n"
  495. "endif()\n"
  496. "\n";
  497. /* clang-format on */
  498. }
  499. // Ask each install generator to write its code.
  500. cmPolicies::PolicyStatus status = this->GetPolicyStatus(cmPolicies::CMP0082);
  501. std::vector<cmInstallGenerator*> const& installers =
  502. this->Makefile->GetInstallGenerators();
  503. bool haveSubdirectoryInstall = false;
  504. bool haveInstallAfterSubdirectory = false;
  505. if (status == cmPolicies::WARN) {
  506. for (cmInstallGenerator* installer : installers) {
  507. installer->CheckCMP0082(haveSubdirectoryInstall,
  508. haveInstallAfterSubdirectory);
  509. installer->Generate(fout, config, configurationTypes);
  510. }
  511. } else {
  512. for (cmInstallGenerator* installer : installers) {
  513. installer->Generate(fout, config, configurationTypes);
  514. }
  515. }
  516. // Write rules from old-style specification stored in targets.
  517. this->GenerateTargetInstallRules(fout, config, configurationTypes);
  518. // Include install scripts from subdirectories.
  519. switch (status) {
  520. case cmPolicies::WARN:
  521. if (haveInstallAfterSubdirectory &&
  522. this->Makefile->PolicyOptionalWarningEnabled(
  523. "CMAKE_POLICY_WARNING_CMP0082")) {
  524. std::ostringstream e;
  525. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0082) << "\n";
  526. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  527. }
  528. CM_FALLTHROUGH;
  529. case cmPolicies::OLD: {
  530. std::vector<cmStateSnapshot> children =
  531. this->Makefile->GetStateSnapshot().GetChildren();
  532. if (!children.empty()) {
  533. fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
  534. fout << " # Include the install script for each subdirectory.\n";
  535. for (cmStateSnapshot const& c : children) {
  536. if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  537. std::string odir = c.GetDirectory().GetCurrentBinary();
  538. cmSystemTools::ConvertToUnixSlashes(odir);
  539. fout << " include(\"" << odir << "/cmake_install.cmake\")"
  540. << std::endl;
  541. }
  542. }
  543. fout << "\n";
  544. fout << "endif()\n\n";
  545. }
  546. } break;
  547. case cmPolicies::REQUIRED_IF_USED:
  548. case cmPolicies::REQUIRED_ALWAYS:
  549. case cmPolicies::NEW:
  550. // NEW behavior is handled in
  551. // cmInstallSubdirectoryGenerator::GenerateScript()
  552. break;
  553. }
  554. // Record the install manifest.
  555. if (toplevel_install) {
  556. /* clang-format off */
  557. fout <<
  558. "if(CMAKE_INSTALL_COMPONENT)\n"
  559. " set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
  560. "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
  561. "else()\n"
  562. " set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
  563. "endif()\n"
  564. "\n"
  565. "string(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n"
  566. " \"${CMAKE_INSTALL_MANIFEST_FILES}\")\n"
  567. "file(WRITE \"" << homedir << "/${CMAKE_INSTALL_MANIFEST}\"\n"
  568. " \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n";
  569. /* clang-format on */
  570. }
  571. }
  572. void cmLocalGenerator::AddGeneratorTarget(cmGeneratorTarget* gt)
  573. {
  574. this->GeneratorTargets.push_back(gt);
  575. this->GeneratorTargetSearchIndex.emplace(gt->GetName(), gt);
  576. this->GlobalGenerator->IndexGeneratorTarget(gt);
  577. }
  578. void cmLocalGenerator::AddImportedGeneratorTarget(cmGeneratorTarget* gt)
  579. {
  580. this->ImportedGeneratorTargets.emplace(gt->GetName(), gt);
  581. this->GlobalGenerator->IndexGeneratorTarget(gt);
  582. }
  583. void cmLocalGenerator::AddOwnedImportedGeneratorTarget(cmGeneratorTarget* gt)
  584. {
  585. this->OwnedImportedGeneratorTargets.push_back(gt);
  586. }
  587. cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
  588. const std::string& name) const
  589. {
  590. auto ti = this->GeneratorTargetSearchIndex.find(name);
  591. if (ti != this->GeneratorTargetSearchIndex.end()) {
  592. return ti->second;
  593. }
  594. return nullptr;
  595. }
  596. void cmLocalGenerator::ComputeTargetManifest()
  597. {
  598. // Collect the set of configuration types.
  599. std::vector<std::string> configNames;
  600. this->Makefile->GetConfigurations(configNames);
  601. if (configNames.empty()) {
  602. configNames.emplace_back();
  603. }
  604. // Add our targets to the manifest for each configuration.
  605. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  606. for (cmGeneratorTarget* target : targets) {
  607. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  608. continue;
  609. }
  610. for (std::string const& c : configNames) {
  611. target->ComputeTargetManifest(c);
  612. }
  613. }
  614. }
  615. bool cmLocalGenerator::ComputeTargetCompileFeatures()
  616. {
  617. // Collect the set of configuration types.
  618. std::vector<std::string> configNames;
  619. this->Makefile->GetConfigurations(configNames);
  620. if (configNames.empty()) {
  621. configNames.emplace_back();
  622. }
  623. // Process compile features of all targets.
  624. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  625. for (cmGeneratorTarget* target : targets) {
  626. for (std::string const& c : configNames) {
  627. if (!target->ComputeCompileFeatures(c)) {
  628. return false;
  629. }
  630. }
  631. }
  632. return true;
  633. }
  634. bool cmLocalGenerator::IsRootMakefile() const
  635. {
  636. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  637. }
  638. cmState* cmLocalGenerator::GetState() const
  639. {
  640. return this->GlobalGenerator->GetCMakeInstance()->GetState();
  641. }
  642. cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
  643. {
  644. return this->Makefile->GetStateSnapshot();
  645. }
  646. const char* cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
  647. const std::string& prop)
  648. {
  649. if (target) {
  650. return target->GetProperty(prop);
  651. }
  652. return this->Makefile->GetProperty(prop);
  653. }
  654. std::string cmLocalGenerator::ConvertToIncludeReference(
  655. std::string const& path, OutputFormat format, bool forceFullPaths)
  656. {
  657. static_cast<void>(forceFullPaths);
  658. return this->ConvertToOutputForExisting(path, format);
  659. }
  660. std::string cmLocalGenerator::GetIncludeFlags(
  661. const std::vector<std::string>& includeDirs, cmGeneratorTarget* target,
  662. const std::string& lang, bool forceFullPaths, bool forResponseFile,
  663. const std::string& config)
  664. {
  665. if (lang.empty()) {
  666. return "";
  667. }
  668. std::vector<std::string> includes = includeDirs;
  669. MoveSystemIncludesToEnd(includes, config, lang, target);
  670. OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
  671. std::ostringstream includeFlags;
  672. std::string const& includeFlag =
  673. this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
  674. const char* sep =
  675. this->Makefile->GetDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_SEP_", lang));
  676. bool quotePaths = false;
  677. if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
  678. quotePaths = true;
  679. }
  680. bool repeatFlag = true;
  681. // should the include flag be repeated like ie. -IA -IB
  682. if (!sep) {
  683. sep = " ";
  684. } else {
  685. // if there is a separator then the flag is not repeated but is only
  686. // given once i.e. -classpath a:b:c
  687. repeatFlag = false;
  688. }
  689. // Support special system include flag if it is available and the
  690. // normal flag is repeated for each directory.
  691. const char* sysIncludeFlag = nullptr;
  692. if (repeatFlag) {
  693. sysIncludeFlag = this->Makefile->GetDefinition(
  694. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
  695. }
  696. const char* fwSearchFlag = this->Makefile->GetDefinition(
  697. cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
  698. const char* sysFwSearchFlag = this->Makefile->GetDefinition(
  699. cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
  700. bool flagUsed = false;
  701. std::set<std::string> emitted;
  702. #ifdef __APPLE__
  703. emitted.insert("/System/Library/Frameworks");
  704. #endif
  705. for (std::string const& i : includes) {
  706. if (fwSearchFlag && *fwSearchFlag && this->Makefile->IsOn("APPLE") &&
  707. cmSystemTools::IsPathToFramework(i)) {
  708. std::string const frameworkDir =
  709. cmSystemTools::CollapseFullPath(cmStrCat(i, "/../"));
  710. if (emitted.insert(frameworkDir).second) {
  711. if (sysFwSearchFlag && target &&
  712. target->IsSystemIncludeDirectory(i, config, lang)) {
  713. includeFlags << sysFwSearchFlag;
  714. } else {
  715. includeFlags << fwSearchFlag;
  716. }
  717. includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
  718. << " ";
  719. }
  720. continue;
  721. }
  722. if (!flagUsed || repeatFlag) {
  723. if (sysIncludeFlag && target &&
  724. target->IsSystemIncludeDirectory(i, config, lang)) {
  725. includeFlags << sysIncludeFlag;
  726. } else {
  727. includeFlags << includeFlag;
  728. }
  729. flagUsed = true;
  730. }
  731. std::string includePath =
  732. this->ConvertToIncludeReference(i, shellFormat, forceFullPaths);
  733. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  734. includeFlags << "\"";
  735. }
  736. includeFlags << includePath;
  737. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  738. includeFlags << "\"";
  739. }
  740. includeFlags << sep;
  741. }
  742. std::string flags = includeFlags.str();
  743. // remove trailing separators
  744. if ((sep[0] != ' ') && !flags.empty() && flags.back() == sep[0]) {
  745. flags.back() = ' ';
  746. }
  747. return flags;
  748. }
  749. void cmLocalGenerator::AddCompileOptions(std::string& flags,
  750. cmGeneratorTarget* target,
  751. const std::string& lang,
  752. const std::string& config)
  753. {
  754. std::vector<BT<std::string>> tmpFlags;
  755. this->AddCompileOptions(tmpFlags, target, lang, config);
  756. this->AppendFlags(flags, tmpFlags);
  757. }
  758. void cmLocalGenerator::AddCompileOptions(std::vector<BT<std::string>>& flags,
  759. cmGeneratorTarget* target,
  760. const std::string& lang,
  761. const std::string& config)
  762. {
  763. std::string langFlagRegexVar = std::string("CMAKE_") + lang + "_FLAG_REGEX";
  764. if (const char* langFlagRegexStr =
  765. this->Makefile->GetDefinition(langFlagRegexVar)) {
  766. // Filter flags acceptable to this language.
  767. if (const char* targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  768. std::vector<std::string> opts;
  769. cmSystemTools::ParseWindowsCommandLine(targetFlags, opts);
  770. // Re-escape these flags since COMPILE_FLAGS were already parsed
  771. // as a command line above.
  772. std::string compileOpts;
  773. this->AppendCompileOptions(compileOpts, opts, langFlagRegexStr);
  774. if (!compileOpts.empty()) {
  775. flags.emplace_back(std::move(compileOpts));
  776. }
  777. }
  778. std::vector<BT<std::string>> targetCompileOpts =
  779. target->GetCompileOptions(config, lang);
  780. // COMPILE_OPTIONS are escaped.
  781. this->AppendCompileOptions(flags, targetCompileOpts, langFlagRegexStr);
  782. } else {
  783. // Use all flags.
  784. if (const char* targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  785. // COMPILE_FLAGS are not escaped for historical reasons.
  786. std::string compileFlags;
  787. this->AppendFlags(compileFlags, targetFlags);
  788. if (!compileFlags.empty()) {
  789. flags.emplace_back(std::move(compileFlags));
  790. }
  791. }
  792. std::vector<BT<std::string>> targetCompileOpts =
  793. target->GetCompileOptions(config, lang);
  794. // COMPILE_OPTIONS are escaped.
  795. this->AppendCompileOptions(flags, targetCompileOpts);
  796. }
  797. for (auto const& it : target->GetMaxLanguageStandards()) {
  798. const char* standard = target->GetProperty(it.first + "_STANDARD");
  799. if (!standard) {
  800. continue;
  801. }
  802. if (this->Makefile->IsLaterStandard(it.first, standard, it.second)) {
  803. std::ostringstream e;
  804. e << "The COMPILE_FEATURES property of target \"" << target->GetName()
  805. << "\" was evaluated when computing the link "
  806. "implementation, and the \""
  807. << it.first << "_STANDARD\" was \"" << it.second
  808. << "\" for that computation. Computing the "
  809. "COMPILE_FEATURES based on the link implementation resulted in a "
  810. "higher \""
  811. << it.first << "_STANDARD\" \"" << standard
  812. << "\". "
  813. "This is not permitted. The COMPILE_FEATURES may not both depend "
  814. "on "
  815. "and be depended on by the link implementation."
  816. << std::endl;
  817. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  818. return;
  819. }
  820. }
  821. std::string compReqFlag;
  822. this->AddCompilerRequirementFlag(compReqFlag, target, lang);
  823. if (!compReqFlag.empty()) {
  824. flags.emplace_back(std::move(compReqFlag));
  825. }
  826. // Add compile flag for the MSVC compiler only.
  827. cmMakefile* mf = this->GetMakefile();
  828. if (const char* jmc =
  829. mf->GetDefinition("CMAKE_" + lang + "_COMPILE_OPTIONS_JMC")) {
  830. // Handle Just My Code debugging flags, /JMC.
  831. // If the target is a Managed C++ one, /JMC is not compatible.
  832. if (target->GetManagedType(config) !=
  833. cmGeneratorTarget::ManagedType::Managed) {
  834. // add /JMC flags if target property VS_JUST_MY_CODE_DEBUGGING is set
  835. // to ON
  836. if (char const* jmcExprGen =
  837. target->GetProperty("VS_JUST_MY_CODE_DEBUGGING")) {
  838. std::string isJMCEnabled =
  839. cmGeneratorExpression::Evaluate(jmcExprGen, this, config);
  840. if (cmIsOn(isJMCEnabled)) {
  841. std::vector<std::string> optVec = cmExpandedList(jmc);
  842. std::string jmcFlags;
  843. this->AppendCompileOptions(jmcFlags, optVec);
  844. if (!jmcFlags.empty()) {
  845. flags.emplace_back(std::move(jmcFlags));
  846. }
  847. }
  848. }
  849. }
  850. }
  851. }
  852. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit(
  853. cmGeneratorTarget const* target, std::string const& lang,
  854. std::string const& config, bool stripImplicitDirs,
  855. bool appendAllImplicitDirs) const
  856. {
  857. std::vector<BT<std::string>> result;
  858. // Do not repeat an include path.
  859. std::set<std::string> emitted;
  860. auto emitDir = [&result, &emitted](std::string const& dir) {
  861. if (emitted.insert(dir).second) {
  862. result.emplace_back(dir);
  863. }
  864. };
  865. auto emitBT = [&result, &emitted](BT<std::string> const& dir) {
  866. if (emitted.insert(dir.Value).second) {
  867. result.emplace_back(dir);
  868. }
  869. };
  870. // When automatic include directories are requested for a build then
  871. // include the source and binary directories at the beginning of the
  872. // include path to approximate include file behavior for an
  873. // in-source build. This does not account for the case of a source
  874. // file in a subdirectory of the current source directory but we
  875. // cannot fix this because not all native build tools support
  876. // per-source-file include paths.
  877. if (this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR")) {
  878. // Current binary directory
  879. emitDir(this->StateSnapshot.GetDirectory().GetCurrentBinary());
  880. // Current source directory
  881. emitDir(this->StateSnapshot.GetDirectory().GetCurrentSource());
  882. }
  883. if (!target) {
  884. return result;
  885. }
  886. // Standard include directories to be added unconditionally at the end.
  887. // These are intended to simulate additional implicit include directories.
  888. std::vector<std::string> userStandardDirs;
  889. {
  890. std::string const value = this->Makefile->GetSafeDefinition(
  891. cmStrCat("CMAKE_", lang, "_STANDARD_INCLUDE_DIRECTORIES"));
  892. cmExpandList(value, userStandardDirs);
  893. for (std::string& usd : userStandardDirs) {
  894. cmSystemTools::ConvertToUnixSlashes(usd);
  895. }
  896. }
  897. // Implicit include directories
  898. std::vector<std::string> implicitDirs;
  899. std::set<std::string> implicitSet;
  900. // Include directories to be excluded as if they were implicit.
  901. std::set<std::string> implicitExclude;
  902. {
  903. // Raw list of implicit include directories
  904. // Start with "standard" directories that we unconditionally add below.
  905. std::vector<std::string> impDirVec = userStandardDirs;
  906. // Load implicit include directories for this language.
  907. // We ignore this for Fortran because:
  908. // * There are no standard library headers to avoid overriding.
  909. // * Compilers like gfortran do not search their own implicit include
  910. // directories for modules ('.mod' files).
  911. if (lang != "Fortran") {
  912. const char* value = this->Makefile->GetDefinition(
  913. cmStrCat("CMAKE_", lang, "_IMPLICIT_INCLUDE_DIRECTORIES"));
  914. if (value != nullptr) {
  915. size_t const impDirVecOldSize = impDirVec.size();
  916. cmExpandList(value, impDirVec);
  917. // FIXME: Use cmRange with 'advance()' when it supports non-const.
  918. for (size_t i = impDirVecOldSize; i < impDirVec.size(); ++i) {
  919. cmSystemTools::ConvertToUnixSlashes(impDirVec[i]);
  920. }
  921. }
  922. }
  923. // The Platform/UnixPaths module used to hard-code /usr/include for C, CXX,
  924. // and CUDA in CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES, but those
  925. // variables are now computed. On macOS the /usr/include directory is
  926. // inside the platform SDK so the computed value does not contain it
  927. // directly. In this case adding -I/usr/include can hide SDK headers so we
  928. // must still exclude it.
  929. if ((lang == "C" || lang == "CXX" || lang == "CUDA") &&
  930. !cmContains(impDirVec, "/usr/include") &&
  931. std::find_if(impDirVec.begin(), impDirVec.end(),
  932. [](std::string const& d) {
  933. return cmHasLiteralSuffix(d, "/usr/include");
  934. }) != impDirVec.end()) {
  935. // Only exclude this hard coded path for backwards compatibility.
  936. implicitExclude.emplace("/usr/include");
  937. }
  938. for (std::string const& i : impDirVec) {
  939. if (implicitSet.insert(cmSystemTools::GetRealPath(i)).second) {
  940. implicitDirs.emplace_back(i);
  941. }
  942. }
  943. }
  944. // Checks if this is not an excluded (implicit) include directory.
  945. auto notExcluded = [this, &implicitSet, &implicitExclude,
  946. &lang](std::string const& dir) {
  947. return (
  948. // Do not exclude directories that are not in an excluded set.
  949. ((!cmContains(implicitSet, cmSystemTools::GetRealPath(dir))) &&
  950. (!cmContains(implicitExclude, dir)))
  951. // Do not exclude entries of the CPATH environment variable even though
  952. // they are implicitly searched by the compiler. They are meant to be
  953. // user-specified directories that can be re-ordered or converted to
  954. // -isystem without breaking real compiler builtin headers.
  955. || ((lang == "C" || lang == "CXX") && cmContains(this->EnvCPATH, dir)));
  956. };
  957. // Get the target-specific include directories.
  958. std::vector<BT<std::string>> userDirs =
  959. target->GetIncludeDirectories(config, lang);
  960. // Support putting all the in-project include directories first if
  961. // it is requested by the project.
  962. if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
  963. std::string const& topSourceDir = this->GetState()->GetSourceDirectory();
  964. std::string const& topBinaryDir = this->GetState()->GetBinaryDirectory();
  965. for (BT<std::string> const& udr : userDirs) {
  966. // Emit this directory only if it is a subdirectory of the
  967. // top-level source or binary tree.
  968. if (cmSystemTools::ComparePath(udr.Value, topSourceDir) ||
  969. cmSystemTools::ComparePath(udr.Value, topBinaryDir) ||
  970. cmSystemTools::IsSubDirectory(udr.Value, topSourceDir) ||
  971. cmSystemTools::IsSubDirectory(udr.Value, topBinaryDir)) {
  972. if (notExcluded(udr.Value)) {
  973. emitBT(udr);
  974. }
  975. }
  976. }
  977. }
  978. // Emit remaining non implicit user direcories.
  979. for (BT<std::string> const& udr : userDirs) {
  980. if (notExcluded(udr.Value)) {
  981. emitBT(udr);
  982. }
  983. }
  984. // Sort result
  985. MoveSystemIncludesToEnd(result, config, lang, target);
  986. // Append standard include directories for this language.
  987. userDirs.reserve(userDirs.size() + userStandardDirs.size());
  988. for (std::string& usd : userStandardDirs) {
  989. emitDir(usd);
  990. userDirs.emplace_back(std::move(usd));
  991. }
  992. // Append compiler implicit include directories
  993. if (!stripImplicitDirs) {
  994. // Append implicit directories that were requested by the user only
  995. for (BT<std::string> const& udr : userDirs) {
  996. if (cmContains(implicitSet, cmSystemTools::GetRealPath(udr.Value))) {
  997. emitBT(udr);
  998. }
  999. }
  1000. // Append remaining implicit directories (on demand)
  1001. if (appendAllImplicitDirs) {
  1002. for (std::string& imd : implicitDirs) {
  1003. emitDir(imd);
  1004. }
  1005. }
  1006. }
  1007. return result;
  1008. }
  1009. void cmLocalGenerator::GetIncludeDirectoriesImplicit(
  1010. std::vector<std::string>& dirs, cmGeneratorTarget const* target,
  1011. const std::string& lang, const std::string& config, bool stripImplicitDirs,
  1012. bool appendAllImplicitDirs) const
  1013. {
  1014. std::vector<BT<std::string>> tmp = this->GetIncludeDirectoriesImplicit(
  1015. target, lang, config, stripImplicitDirs, appendAllImplicitDirs);
  1016. dirs.reserve(dirs.size() + tmp.size());
  1017. for (BT<std::string>& v : tmp) {
  1018. dirs.emplace_back(std::move(v.Value));
  1019. }
  1020. }
  1021. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectories(
  1022. cmGeneratorTarget const* target, std::string const& lang,
  1023. std::string const& config) const
  1024. {
  1025. return this->GetIncludeDirectoriesImplicit(target, lang, config);
  1026. }
  1027. void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
  1028. cmGeneratorTarget const* target,
  1029. const std::string& lang,
  1030. const std::string& config) const
  1031. {
  1032. this->GetIncludeDirectoriesImplicit(dirs, target, lang, config);
  1033. }
  1034. void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
  1035. std::string const& config,
  1036. std::string const& linkLanguage,
  1037. cmGeneratorTarget* target)
  1038. {
  1039. std::vector<BT<std::string>> tmpFlags =
  1040. this->GetStaticLibraryFlags(config, linkLanguage, target);
  1041. this->AppendFlags(flags, tmpFlags);
  1042. }
  1043. std::vector<BT<std::string>> cmLocalGenerator::GetStaticLibraryFlags(
  1044. std::string const& config, std::string const& linkLanguage,
  1045. cmGeneratorTarget* target)
  1046. {
  1047. std::vector<BT<std::string>> flags;
  1048. if (linkLanguage != "Swift") {
  1049. std::string staticLibFlags;
  1050. this->AppendFlags(
  1051. staticLibFlags,
  1052. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
  1053. if (!config.empty()) {
  1054. std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + config;
  1055. this->AppendFlags(staticLibFlags,
  1056. this->Makefile->GetSafeDefinition(name));
  1057. }
  1058. if (!staticLibFlags.empty()) {
  1059. flags.emplace_back(std::move(staticLibFlags));
  1060. }
  1061. }
  1062. std::string staticLibFlags;
  1063. this->AppendFlags(staticLibFlags,
  1064. target->GetSafeProperty("STATIC_LIBRARY_FLAGS"));
  1065. if (!config.empty()) {
  1066. std::string name = "STATIC_LIBRARY_FLAGS_" + config;
  1067. this->AppendFlags(staticLibFlags, target->GetSafeProperty(name));
  1068. }
  1069. if (!staticLibFlags.empty()) {
  1070. flags.emplace_back(std::move(staticLibFlags));
  1071. }
  1072. std::vector<BT<std::string>> staticLibOpts =
  1073. target->GetStaticLibraryLinkOptions(config, linkLanguage);
  1074. // STATIC_LIBRARY_OPTIONS are escaped.
  1075. this->AppendCompileOptions(flags, staticLibOpts);
  1076. return flags;
  1077. }
  1078. void cmLocalGenerator::GetTargetFlags(
  1079. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1080. std::string& linkLibs, std::string& flags, std::string& linkFlags,
  1081. std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
  1082. {
  1083. std::vector<BT<std::string>> linkFlagsList;
  1084. std::vector<BT<std::string>> linkPathList;
  1085. std::vector<BT<std::string>> linkLibsList;
  1086. this->GetTargetFlags(linkLineComputer, config, linkLibsList, flags,
  1087. linkFlagsList, frameworkPath, linkPathList, target);
  1088. this->AppendFlags(linkFlags, linkFlagsList);
  1089. this->AppendFlags(linkPath, linkPathList);
  1090. this->AppendFlags(linkLibs, linkLibsList);
  1091. }
  1092. void cmLocalGenerator::GetTargetFlags(
  1093. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1094. std::vector<BT<std::string>>& linkLibs, std::string& flags,
  1095. std::vector<BT<std::string>>& linkFlags, std::string& frameworkPath,
  1096. std::vector<BT<std::string>>& linkPath, cmGeneratorTarget* target)
  1097. {
  1098. const std::string buildType = cmSystemTools::UpperCase(config);
  1099. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1100. const char* libraryLinkVariable =
  1101. "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
  1102. const std::string linkLanguage =
  1103. linkLineComputer->GetLinkerLanguage(target, buildType);
  1104. switch (target->GetType()) {
  1105. case cmStateEnums::STATIC_LIBRARY:
  1106. linkFlags = this->GetStaticLibraryFlags(buildType, linkLanguage, target);
  1107. if (pcli && dynamic_cast<cmLinkLineDeviceComputer*>(linkLineComputer)) {
  1108. // Compute the required cuda device link libraries when
  1109. // resolving cuda device symbols
  1110. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1111. frameworkPath, linkPath);
  1112. }
  1113. break;
  1114. case cmStateEnums::MODULE_LIBRARY:
  1115. libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
  1116. CM_FALLTHROUGH;
  1117. case cmStateEnums::SHARED_LIBRARY: {
  1118. std::string sharedLibFlags;
  1119. if (linkLanguage != "Swift") {
  1120. sharedLibFlags = cmStrCat(
  1121. this->Makefile->GetSafeDefinition(libraryLinkVariable), ' ');
  1122. if (!buildType.empty()) {
  1123. std::string build = cmStrCat(libraryLinkVariable, '_', buildType);
  1124. sharedLibFlags += this->Makefile->GetSafeDefinition(build);
  1125. sharedLibFlags += " ";
  1126. }
  1127. if (this->Makefile->IsOn("WIN32") &&
  1128. !(this->Makefile->IsOn("CYGWIN") ||
  1129. this->Makefile->IsOn("MINGW"))) {
  1130. std::vector<cmSourceFile*> sources;
  1131. target->GetSourceFiles(sources, buildType);
  1132. std::string defFlag =
  1133. this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  1134. for (cmSourceFile* sf : sources) {
  1135. if (sf->GetExtension() == "def") {
  1136. sharedLibFlags += defFlag;
  1137. sharedLibFlags += this->ConvertToOutputFormat(
  1138. cmSystemTools::CollapseFullPath(sf->ResolveFullPath()), SHELL);
  1139. sharedLibFlags += " ";
  1140. }
  1141. }
  1142. }
  1143. }
  1144. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1145. if (targetLinkFlags) {
  1146. sharedLibFlags += targetLinkFlags;
  1147. sharedLibFlags += " ";
  1148. }
  1149. if (!buildType.empty()) {
  1150. targetLinkFlags =
  1151. target->GetProperty(cmStrCat("LINK_FLAGS_", buildType));
  1152. if (targetLinkFlags) {
  1153. sharedLibFlags += targetLinkFlags;
  1154. sharedLibFlags += " ";
  1155. }
  1156. }
  1157. if (!sharedLibFlags.empty()) {
  1158. linkFlags.emplace_back(std::move(sharedLibFlags));
  1159. }
  1160. std::vector<BT<std::string>> linkOpts =
  1161. target->GetLinkOptions(config, linkLanguage);
  1162. // LINK_OPTIONS are escaped.
  1163. this->AppendCompileOptions(linkFlags, linkOpts);
  1164. if (pcli) {
  1165. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1166. frameworkPath, linkPath);
  1167. }
  1168. } break;
  1169. case cmStateEnums::EXECUTABLE: {
  1170. std::string exeFlags;
  1171. if (linkLanguage != "Swift") {
  1172. exeFlags = this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
  1173. exeFlags += " ";
  1174. if (!buildType.empty()) {
  1175. exeFlags += this->Makefile->GetSafeDefinition(
  1176. cmStrCat("CMAKE_EXE_LINKER_FLAGS_", buildType));
  1177. exeFlags += " ";
  1178. }
  1179. if (linkLanguage.empty()) {
  1180. cmSystemTools::Error(
  1181. "CMake can not determine linker language for target: " +
  1182. target->GetName());
  1183. return;
  1184. }
  1185. if (target->GetPropertyAsBool("WIN32_EXECUTABLE")) {
  1186. exeFlags +=
  1187. this->Makefile->GetSafeDefinition("CMAKE_CREATE_WIN32_EXE");
  1188. exeFlags += " ";
  1189. } else {
  1190. exeFlags +=
  1191. this->Makefile->GetSafeDefinition("CMAKE_CREATE_CONSOLE_EXE");
  1192. exeFlags += " ";
  1193. }
  1194. if (target->IsExecutableWithExports()) {
  1195. exeFlags += this->Makefile->GetSafeDefinition(
  1196. cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"));
  1197. exeFlags += " ";
  1198. }
  1199. }
  1200. this->AddLanguageFlagsForLinking(flags, target, linkLanguage, buildType);
  1201. if (pcli) {
  1202. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1203. frameworkPath, linkPath);
  1204. }
  1205. if (cmIsOn(this->Makefile->GetDefinition("BUILD_SHARED_LIBS"))) {
  1206. std::string sFlagVar = std::string("CMAKE_SHARED_BUILD_") +
  1207. linkLanguage + std::string("_FLAGS");
  1208. exeFlags += this->Makefile->GetSafeDefinition(sFlagVar);
  1209. exeFlags += " ";
  1210. }
  1211. std::string cmp0065Flags =
  1212. this->GetLinkLibsCMP0065(linkLanguage, *target);
  1213. if (!cmp0065Flags.empty()) {
  1214. exeFlags += cmp0065Flags;
  1215. exeFlags += " ";
  1216. }
  1217. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1218. if (targetLinkFlags) {
  1219. exeFlags += targetLinkFlags;
  1220. exeFlags += " ";
  1221. }
  1222. if (!buildType.empty()) {
  1223. targetLinkFlags =
  1224. target->GetProperty(cmStrCat("LINK_FLAGS_", buildType));
  1225. if (targetLinkFlags) {
  1226. exeFlags += targetLinkFlags;
  1227. exeFlags += " ";
  1228. }
  1229. }
  1230. if (!exeFlags.empty()) {
  1231. linkFlags.emplace_back(std::move(exeFlags));
  1232. }
  1233. std::vector<BT<std::string>> linkOpts =
  1234. target->GetLinkOptions(config, linkLanguage);
  1235. // LINK_OPTIONS are escaped.
  1236. this->AppendCompileOptions(linkFlags, linkOpts);
  1237. } break;
  1238. default:
  1239. break;
  1240. }
  1241. std::string extraLinkFlags;
  1242. this->AppendPositionIndependentLinkerFlags(extraLinkFlags, target, config,
  1243. linkLanguage);
  1244. this->AppendIPOLinkerFlags(extraLinkFlags, target, config, linkLanguage);
  1245. if (!extraLinkFlags.empty()) {
  1246. linkFlags.emplace_back(std::move(extraLinkFlags));
  1247. }
  1248. }
  1249. void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
  1250. std::string const& config,
  1251. std::string const& lang,
  1252. std::string& flags)
  1253. {
  1254. std::vector<BT<std::string>> tmpFlags =
  1255. this->GetTargetCompileFlags(target, config, lang);
  1256. this->AppendFlags(flags, tmpFlags);
  1257. }
  1258. std::vector<BT<std::string>> cmLocalGenerator::GetTargetCompileFlags(
  1259. cmGeneratorTarget* target, std::string const& config,
  1260. std::string const& lang)
  1261. {
  1262. std::vector<BT<std::string>> flags;
  1263. std::string compileFlags;
  1264. cmMakefile* mf = this->GetMakefile();
  1265. // Add language-specific flags.
  1266. this->AddLanguageFlags(compileFlags, target, lang, config);
  1267. if (target->IsIPOEnabled(lang, config)) {
  1268. this->AppendFeatureOptions(compileFlags, lang, "IPO");
  1269. }
  1270. this->AddArchitectureFlags(compileFlags, target, lang, config);
  1271. if (lang == "Fortran") {
  1272. this->AppendFlags(compileFlags,
  1273. this->GetTargetFortranFlags(target, config));
  1274. }
  1275. this->AddCMP0018Flags(compileFlags, target, lang, config);
  1276. this->AddVisibilityPresetFlags(compileFlags, target, lang);
  1277. this->AppendFlags(compileFlags, mf->GetDefineFlags());
  1278. this->AppendFlags(compileFlags,
  1279. this->GetFrameworkFlags(lang, config, target));
  1280. if (!compileFlags.empty()) {
  1281. flags.emplace_back(std::move(compileFlags));
  1282. }
  1283. this->AddCompileOptions(flags, target, lang, config);
  1284. return flags;
  1285. }
  1286. static std::string GetFrameworkFlags(const std::string& lang,
  1287. const std::string& config,
  1288. cmGeneratorTarget* target)
  1289. {
  1290. cmLocalGenerator* lg = target->GetLocalGenerator();
  1291. cmMakefile* mf = lg->GetMakefile();
  1292. if (!mf->IsOn("APPLE")) {
  1293. return std::string();
  1294. }
  1295. std::string fwSearchFlagVar = "CMAKE_" + lang + "_FRAMEWORK_SEARCH_FLAG";
  1296. const char* fwSearchFlag = mf->GetDefinition(fwSearchFlagVar);
  1297. if (!(fwSearchFlag && *fwSearchFlag)) {
  1298. return std::string();
  1299. }
  1300. std::set<std::string> emitted;
  1301. #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
  1302. emitted.insert("/System/Library/Frameworks");
  1303. #endif
  1304. std::vector<std::string> includes;
  1305. lg->GetIncludeDirectories(includes, target, "C", config);
  1306. // check all include directories for frameworks as this
  1307. // will already have added a -F for the framework
  1308. for (std::string const& include : includes) {
  1309. if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
  1310. std::string frameworkDir = cmStrCat(include, "/../");
  1311. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1312. emitted.insert(frameworkDir);
  1313. }
  1314. }
  1315. std::string flags;
  1316. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1317. std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
  1318. for (std::string const& framework : frameworks) {
  1319. if (emitted.insert(framework).second) {
  1320. flags += fwSearchFlag;
  1321. flags +=
  1322. lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
  1323. flags += " ";
  1324. }
  1325. }
  1326. }
  1327. return flags;
  1328. }
  1329. std::string cmLocalGenerator::GetFrameworkFlags(std::string const& l,
  1330. std::string const& config,
  1331. cmGeneratorTarget* target)
  1332. {
  1333. return ::GetFrameworkFlags(l, config, target);
  1334. }
  1335. void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
  1336. std::string const& config,
  1337. std::string const& lang,
  1338. std::set<std::string>& defines) const
  1339. {
  1340. std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
  1341. for (BT<std::string> const& v : tmp) {
  1342. defines.emplace(v.Value);
  1343. }
  1344. }
  1345. std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
  1346. cmGeneratorTarget const* target, std::string const& config,
  1347. std::string const& lang) const
  1348. {
  1349. std::set<BT<std::string>> defines;
  1350. // Add the export symbol definition for shared library objects.
  1351. if (const std::string* exportMacro = target->GetExportMacro()) {
  1352. this->AppendDefines(defines, *exportMacro);
  1353. }
  1354. // Add preprocessor definitions for this target and configuration.
  1355. std::vector<BT<std::string>> targetDefines =
  1356. target->GetCompileDefinitions(config, lang);
  1357. this->AppendDefines(defines, targetDefines);
  1358. return defines;
  1359. }
  1360. std::string cmLocalGenerator::GetTargetFortranFlags(
  1361. cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
  1362. {
  1363. // Implemented by specific generators that override this.
  1364. return std::string();
  1365. }
  1366. /**
  1367. * Output the linking rules on a command line. For executables,
  1368. * targetLibrary should be a NULL pointer. For libraries, it should point
  1369. * to the name of the library. This will not link a library against itself.
  1370. */
  1371. void cmLocalGenerator::OutputLinkLibraries(
  1372. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1373. std::string& linkLibraries, std::string& frameworkPath,
  1374. std::string& linkPath)
  1375. {
  1376. std::vector<BT<std::string>> linkLibrariesList;
  1377. std::vector<BT<std::string>> linkPathList;
  1378. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibrariesList,
  1379. frameworkPath, linkPathList);
  1380. pcli->AppendValues(linkLibraries, linkLibrariesList);
  1381. pcli->AppendValues(linkPath, linkPathList);
  1382. }
  1383. void cmLocalGenerator::OutputLinkLibraries(
  1384. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1385. std::vector<BT<std::string>>& linkLibraries, std::string& frameworkPath,
  1386. std::vector<BT<std::string>>& linkPath)
  1387. {
  1388. cmComputeLinkInformation& cli = *pcli;
  1389. std::string linkLanguage = cli.GetLinkLanguage();
  1390. std::string libPathFlag;
  1391. if (const char* value = this->Makefile->GetDefinition(
  1392. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
  1393. libPathFlag = value;
  1394. } else {
  1395. libPathFlag =
  1396. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
  1397. }
  1398. std::string libPathTerminator;
  1399. if (const char* value = this->Makefile->GetDefinition(
  1400. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
  1401. libPathTerminator = value;
  1402. } else {
  1403. libPathTerminator =
  1404. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
  1405. }
  1406. // Add standard libraries for this language.
  1407. std::string stdLibString = this->Makefile->GetSafeDefinition(
  1408. cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LIBRARIES"));
  1409. // Append the framework search path flags.
  1410. std::string fwSearchFlag = this->Makefile->GetSafeDefinition(
  1411. cmStrCat("CMAKE_", linkLanguage, "_FRAMEWORK_SEARCH_FLAG"));
  1412. frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
  1413. linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator,
  1414. linkPath);
  1415. linkLineComputer->ComputeLinkLibraries(cli, stdLibString, linkLibraries);
  1416. }
  1417. std::string cmLocalGenerator::GetLinkLibsCMP0065(
  1418. std::string const& linkLanguage, cmGeneratorTarget& tgt) const
  1419. {
  1420. std::string linkFlags;
  1421. // Flags to link an executable to shared libraries.
  1422. if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
  1423. this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
  1424. "TARGET_SUPPORTS_SHARED_LIBS")) {
  1425. bool add_shlib_flags = false;
  1426. switch (tgt.GetPolicyStatusCMP0065()) {
  1427. case cmPolicies::WARN:
  1428. if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
  1429. this->Makefile->PolicyOptionalWarningEnabled(
  1430. "CMAKE_POLICY_WARNING_CMP0065")) {
  1431. std::ostringstream w;
  1432. /* clang-format off */
  1433. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
  1434. "For compatibility with older versions of CMake, "
  1435. "additional flags may be added to export symbols on all "
  1436. "executables regardless of their ENABLE_EXPORTS property.";
  1437. /* clang-format on */
  1438. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  1439. }
  1440. CM_FALLTHROUGH;
  1441. case cmPolicies::OLD:
  1442. // OLD behavior is to always add the flags, except on AIX where
  1443. // we compute symbol exports if ENABLE_EXPORTS is on.
  1444. add_shlib_flags =
  1445. !(tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS"));
  1446. break;
  1447. case cmPolicies::REQUIRED_IF_USED:
  1448. case cmPolicies::REQUIRED_ALWAYS:
  1449. this->IssueMessage(
  1450. MessageType::FATAL_ERROR,
  1451. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
  1452. CM_FALLTHROUGH;
  1453. case cmPolicies::NEW:
  1454. // NEW behavior is to only add the flags if ENABLE_EXPORTS is on,
  1455. // except on AIX where we compute symbol exports.
  1456. add_shlib_flags =
  1457. !tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS");
  1458. break;
  1459. }
  1460. if (add_shlib_flags) {
  1461. linkFlags = this->Makefile->GetSafeDefinition(
  1462. cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", linkLanguage, "_FLAGS"));
  1463. }
  1464. }
  1465. return linkFlags;
  1466. }
  1467. void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
  1468. cmGeneratorTarget const* target,
  1469. const std::string& lang,
  1470. const std::string& config)
  1471. {
  1472. // Only add macOS specific flags on Darwin platforms (macOS and iOS):
  1473. if (this->Makefile->IsOn("APPLE") && this->EmitUniversalBinaryFlags) {
  1474. std::vector<std::string> archs;
  1475. target->GetAppleArchs(config, archs);
  1476. const char* sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  1477. if (sysroot && sysroot[0] == '/' && !sysroot[1]) {
  1478. sysroot = nullptr;
  1479. }
  1480. std::string sysrootFlagVar =
  1481. std::string("CMAKE_") + lang + "_SYSROOT_FLAG";
  1482. const char* sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
  1483. const char* deploymentTarget =
  1484. this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  1485. std::string deploymentTargetFlagVar =
  1486. std::string("CMAKE_") + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
  1487. const char* deploymentTargetFlag =
  1488. this->Makefile->GetDefinition(deploymentTargetFlagVar);
  1489. if (!archs.empty() && !lang.empty() &&
  1490. (lang[0] == 'C' || lang[0] == 'F' || lang[0] == 'O')) {
  1491. for (std::string const& arch : archs) {
  1492. flags += " -arch ";
  1493. flags += arch;
  1494. }
  1495. }
  1496. if (sysrootFlag && *sysrootFlag && sysroot && *sysroot) {
  1497. flags += " ";
  1498. flags += sysrootFlag;
  1499. flags += " ";
  1500. flags += this->ConvertToOutputFormat(sysroot, SHELL);
  1501. }
  1502. if (deploymentTargetFlag && *deploymentTargetFlag && deploymentTarget &&
  1503. *deploymentTarget) {
  1504. flags += " ";
  1505. flags += deploymentTargetFlag;
  1506. flags += deploymentTarget;
  1507. }
  1508. }
  1509. }
  1510. void cmLocalGenerator::AddLanguageFlags(std::string& flags,
  1511. cmGeneratorTarget const* target,
  1512. const std::string& lang,
  1513. const std::string& config)
  1514. {
  1515. // Add language-specific flags.
  1516. this->AddConfigVariableFlags(flags, cmStrCat("CMAKE_", lang, "_FLAGS"),
  1517. config);
  1518. if (lang == "Swift") {
  1519. if (const char* v = target->GetProperty("Swift_LANGUAGE_VERSION")) {
  1520. if (cmSystemTools::VersionCompare(
  1521. cmSystemTools::OP_GREATER_EQUAL,
  1522. this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
  1523. "4.2")) {
  1524. this->AppendFlags(flags, "-swift-version " + std::string(v));
  1525. }
  1526. }
  1527. }
  1528. // Add MSVC runtime library flags. This is activated by the presence
  1529. // of a default selection whether or not it is overridden by a property.
  1530. const char* msvcRuntimeLibraryDefault =
  1531. this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
  1532. if (msvcRuntimeLibraryDefault && *msvcRuntimeLibraryDefault) {
  1533. const char* msvcRuntimeLibraryValue =
  1534. target->GetProperty("MSVC_RUNTIME_LIBRARY");
  1535. if (!msvcRuntimeLibraryValue) {
  1536. msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
  1537. }
  1538. std::string const msvcRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1539. msvcRuntimeLibraryValue, this, config, target);
  1540. if (!msvcRuntimeLibrary.empty()) {
  1541. if (const char* msvcRuntimeLibraryOptions =
  1542. this->Makefile->GetDefinition(
  1543. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1544. msvcRuntimeLibrary)) {
  1545. this->AppendCompileOptions(flags, msvcRuntimeLibraryOptions);
  1546. } else if ((this->Makefile->GetSafeDefinition(
  1547. "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
  1548. this->Makefile->GetSafeDefinition(
  1549. "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
  1550. !cmSystemTools::GetErrorOccuredFlag()) {
  1551. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1552. this->IssueMessage(MessageType::FATAL_ERROR,
  1553. "MSVC_RUNTIME_LIBRARY value '" +
  1554. msvcRuntimeLibrary + "' not known for this " +
  1555. lang + " compiler.");
  1556. }
  1557. }
  1558. }
  1559. }
  1560. void cmLocalGenerator::AddLanguageFlagsForLinking(
  1561. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  1562. const std::string& config)
  1563. {
  1564. if (this->Makefile->IsOn("CMAKE_" + lang +
  1565. "_LINK_WITH_STANDARD_COMPILE_OPTION")) {
  1566. // This toolchain requires use of the language standard flag
  1567. // when linking in order to use the matching standard library.
  1568. // FIXME: If CMake gains an abstraction for standard library
  1569. // selection, this will have to be reconciled with it.
  1570. this->AddCompilerRequirementFlag(flags, target, lang);
  1571. }
  1572. this->AddLanguageFlags(flags, target, lang, config);
  1573. if (target->IsIPOEnabled(lang, config)) {
  1574. this->AppendFeatureOptions(flags, lang, "IPO");
  1575. }
  1576. }
  1577. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  1578. const std::string& name) const
  1579. {
  1580. auto imported = this->ImportedGeneratorTargets.find(name);
  1581. if (imported != this->ImportedGeneratorTargets.end()) {
  1582. return imported->second;
  1583. }
  1584. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  1585. return t;
  1586. }
  1587. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  1588. }
  1589. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  1590. const std::string& config,
  1591. std::string& dep)
  1592. {
  1593. // Older CMake code may specify the dependency using the target
  1594. // output file rather than the target name. Such code would have
  1595. // been written before there was support for target properties that
  1596. // modify the name so stripping down to just the file name should
  1597. // produce the target name in this case.
  1598. std::string name = cmSystemTools::GetFilenameName(inName);
  1599. // If the input name is the empty string, there is no real
  1600. // dependency. Short-circuit the other checks:
  1601. if (name.empty()) {
  1602. return false;
  1603. }
  1604. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  1605. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  1606. }
  1607. // Look for a CMake target with the given name.
  1608. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  1609. // make sure it is not just a coincidence that the target name
  1610. // found is part of the inName
  1611. if (cmSystemTools::FileIsFullPath(inName)) {
  1612. std::string tLocation;
  1613. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  1614. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  1615. tLocation = target->GetLocation(config);
  1616. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  1617. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  1618. }
  1619. std::string depLocation =
  1620. cmSystemTools::GetFilenamePath(std::string(inName));
  1621. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  1622. if (depLocation != tLocation) {
  1623. // it is a full path to a depend that has the same name
  1624. // as a target but is in a different location so do not use
  1625. // the target as the depend
  1626. dep = inName;
  1627. return true;
  1628. }
  1629. }
  1630. switch (target->GetType()) {
  1631. case cmStateEnums::EXECUTABLE:
  1632. case cmStateEnums::STATIC_LIBRARY:
  1633. case cmStateEnums::SHARED_LIBRARY:
  1634. case cmStateEnums::MODULE_LIBRARY:
  1635. case cmStateEnums::UNKNOWN_LIBRARY:
  1636. dep = target->GetLocation(config);
  1637. return true;
  1638. case cmStateEnums::OBJECT_LIBRARY:
  1639. // An object library has no single file on which to depend.
  1640. // This was listed to get the target-level dependency.
  1641. return false;
  1642. case cmStateEnums::INTERFACE_LIBRARY:
  1643. // An interface library has no file on which to depend.
  1644. // This was listed to get the target-level dependency.
  1645. return false;
  1646. case cmStateEnums::UTILITY:
  1647. case cmStateEnums::GLOBAL_TARGET:
  1648. // A utility target has no file on which to depend. This was listed
  1649. // only to get the target-level dependency.
  1650. return false;
  1651. }
  1652. }
  1653. // The name was not that of a CMake target. It must name a file.
  1654. if (cmSystemTools::FileIsFullPath(inName)) {
  1655. // This is a full path. Return it as given.
  1656. dep = inName;
  1657. return true;
  1658. }
  1659. // Check for a source file in this directory that matches the
  1660. // dependency.
  1661. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  1662. dep = sf->ResolveFullPath();
  1663. return true;
  1664. }
  1665. // Treat the name as relative to the source directory in which it
  1666. // was given.
  1667. dep = cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentSource(), '/',
  1668. inName);
  1669. return true;
  1670. }
  1671. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  1672. const std::string& lang, bool shared)
  1673. {
  1674. std::string flagsVar;
  1675. // Add flags for dealing with shared libraries for this language.
  1676. if (shared) {
  1677. this->AppendFlags(flags,
  1678. this->Makefile->GetSafeDefinition(
  1679. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS")));
  1680. }
  1681. }
  1682. void cmLocalGenerator::AddCompilerRequirementFlag(
  1683. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1684. {
  1685. if (lang.empty()) {
  1686. return;
  1687. }
  1688. const char* defaultStd =
  1689. this->Makefile->GetDefinition("CMAKE_" + lang + "_STANDARD_DEFAULT");
  1690. if (!defaultStd || !*defaultStd) {
  1691. // This compiler has no notion of language standard levels.
  1692. return;
  1693. }
  1694. std::string extProp = lang + "_EXTENSIONS";
  1695. bool ext = true;
  1696. if (const char* extPropValue = target->GetProperty(extProp)) {
  1697. if (cmIsOff(extPropValue)) {
  1698. ext = false;
  1699. }
  1700. }
  1701. std::string stdProp = lang + "_STANDARD";
  1702. const char* standardProp = target->GetProperty(stdProp);
  1703. if (!standardProp) {
  1704. if (ext) {
  1705. // No language standard is specified and extensions are not disabled.
  1706. // Check if this compiler needs a flag to enable extensions.
  1707. std::string const option_flag =
  1708. "CMAKE_" + lang + "_EXTENSION_COMPILE_OPTION";
  1709. if (const char* opt =
  1710. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1711. std::vector<std::string> optVec = cmExpandedList(opt);
  1712. for (std::string const& i : optVec) {
  1713. this->AppendFlagEscape(flags, i);
  1714. }
  1715. }
  1716. }
  1717. return;
  1718. }
  1719. std::string const type = ext ? "EXTENSION" : "STANDARD";
  1720. if (target->GetPropertyAsBool(lang + "_STANDARD_REQUIRED")) {
  1721. std::string option_flag =
  1722. "CMAKE_" + lang + standardProp + "_" + type + "_COMPILE_OPTION";
  1723. const char* opt =
  1724. target->Target->GetMakefile()->GetDefinition(option_flag);
  1725. if (!opt) {
  1726. std::ostringstream e;
  1727. e << "Target \"" << target->GetName()
  1728. << "\" requires the language "
  1729. "dialect \""
  1730. << lang << standardProp << "\" "
  1731. << (ext ? "(with compiler extensions)" : "")
  1732. << ", but CMake "
  1733. "does not know the compile flags to use to enable it.";
  1734. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1735. } else {
  1736. std::vector<std::string> optVec = cmExpandedList(opt);
  1737. for (std::string const& i : optVec) {
  1738. this->AppendFlagEscape(flags, i);
  1739. }
  1740. }
  1741. return;
  1742. }
  1743. static std::map<std::string, std::vector<std::string>> langStdMap;
  1744. if (langStdMap.empty()) {
  1745. // Maintain sorted order, most recent first.
  1746. langStdMap["CXX"].emplace_back("20");
  1747. langStdMap["CXX"].emplace_back("17");
  1748. langStdMap["CXX"].emplace_back("14");
  1749. langStdMap["CXX"].emplace_back("11");
  1750. langStdMap["CXX"].emplace_back("98");
  1751. langStdMap["C"].emplace_back("11");
  1752. langStdMap["C"].emplace_back("99");
  1753. langStdMap["C"].emplace_back("90");
  1754. langStdMap["CUDA"].emplace_back("14");
  1755. langStdMap["CUDA"].emplace_back("11");
  1756. langStdMap["CUDA"].emplace_back("98");
  1757. }
  1758. std::string standard(standardProp);
  1759. std::vector<std::string>& stds = langStdMap[lang];
  1760. auto stdIt = std::find(stds.begin(), stds.end(), standard);
  1761. if (stdIt == stds.end()) {
  1762. std::string e =
  1763. lang + "_STANDARD is set to invalid value '" + standard + "'";
  1764. this->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  1765. MessageType::FATAL_ERROR, e, target->GetBacktrace());
  1766. return;
  1767. }
  1768. auto defaultStdIt = std::find(stds.begin(), stds.end(), defaultStd);
  1769. if (defaultStdIt == stds.end()) {
  1770. std::string e = "CMAKE_" + lang +
  1771. "_STANDARD_DEFAULT is set to invalid value '" + std::string(defaultStd) +
  1772. "'";
  1773. this->IssueMessage(MessageType::INTERNAL_ERROR, e);
  1774. return;
  1775. }
  1776. // If the standard requested is older than the compiler's default
  1777. // then we need to use a flag to change it. The comparison is
  1778. // greater-or-equal because the standards are stored in backward
  1779. // chronological order.
  1780. if (stdIt >= defaultStdIt) {
  1781. std::string option_flag =
  1782. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  1783. std::string const& opt =
  1784. target->Target->GetMakefile()->GetRequiredDefinition(option_flag);
  1785. std::vector<std::string> optVec = cmExpandedList(opt);
  1786. for (std::string const& i : optVec) {
  1787. this->AppendFlagEscape(flags, i);
  1788. }
  1789. return;
  1790. }
  1791. // The standard requested is at least as new as the compiler's default,
  1792. // and the standard request is not required. Decay to the newest standard
  1793. // for which a flag is defined.
  1794. for (; stdIt < defaultStdIt; ++stdIt) {
  1795. std::string option_flag =
  1796. cmStrCat("CMAKE_", lang, *stdIt, "_", type, "_COMPILE_OPTION");
  1797. if (const char* opt =
  1798. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1799. std::vector<std::string> optVec = cmExpandedList(opt);
  1800. for (std::string const& i : optVec) {
  1801. this->AppendFlagEscape(flags, i);
  1802. }
  1803. return;
  1804. }
  1805. }
  1806. }
  1807. static void AddVisibilityCompileOption(std::string& flags,
  1808. cmGeneratorTarget const* target,
  1809. cmLocalGenerator* lg,
  1810. const std::string& lang,
  1811. std::string* warnCMP0063)
  1812. {
  1813. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  1814. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1815. if (!opt) {
  1816. return;
  1817. }
  1818. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  1819. const char* prop = target->GetProperty(flagDefine);
  1820. if (!prop) {
  1821. return;
  1822. }
  1823. if (warnCMP0063) {
  1824. *warnCMP0063 += " " + flagDefine + "\n";
  1825. return;
  1826. }
  1827. if (strcmp(prop, "hidden") != 0 && strcmp(prop, "default") != 0 &&
  1828. strcmp(prop, "protected") != 0 && strcmp(prop, "internal") != 0) {
  1829. std::ostringstream e;
  1830. e << "Target " << target->GetName() << " uses unsupported value \"" << prop
  1831. << "\" for " << flagDefine << "."
  1832. << " The supported values are: default, hidden, protected, and "
  1833. "internal.";
  1834. cmSystemTools::Error(e.str());
  1835. return;
  1836. }
  1837. std::string option = std::string(opt) + prop;
  1838. lg->AppendFlags(flags, option);
  1839. }
  1840. static void AddInlineVisibilityCompileOption(std::string& flags,
  1841. cmGeneratorTarget const* target,
  1842. cmLocalGenerator* lg,
  1843. std::string* warnCMP0063)
  1844. {
  1845. std::string compileOption =
  1846. "CMAKE_CXX_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN";
  1847. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1848. if (!opt) {
  1849. return;
  1850. }
  1851. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  1852. if (!prop) {
  1853. return;
  1854. }
  1855. if (warnCMP0063) {
  1856. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  1857. return;
  1858. }
  1859. lg->AppendFlags(flags, opt);
  1860. }
  1861. void cmLocalGenerator::AddVisibilityPresetFlags(
  1862. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1863. {
  1864. if (lang.empty()) {
  1865. return;
  1866. }
  1867. std::string warnCMP0063;
  1868. std::string* pWarnCMP0063 = nullptr;
  1869. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1870. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  1871. !target->IsExecutableWithExports()) {
  1872. switch (target->GetPolicyStatusCMP0063()) {
  1873. case cmPolicies::OLD:
  1874. return;
  1875. case cmPolicies::WARN:
  1876. pWarnCMP0063 = &warnCMP0063;
  1877. break;
  1878. default:
  1879. break;
  1880. }
  1881. }
  1882. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  1883. if (lang == "CXX") {
  1884. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063);
  1885. }
  1886. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  1887. std::ostringstream w;
  1888. /* clang-format off */
  1889. w <<
  1890. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  1891. "Target \"" << target->GetName() << "\" of "
  1892. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  1893. "has the following visibility properties set for " << lang << ":\n" <<
  1894. warnCMP0063 <<
  1895. "For compatibility CMake is not honoring them for this target.";
  1896. /* clang-format on */
  1897. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  1898. MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  1899. }
  1900. }
  1901. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  1902. cmGeneratorTarget const* target,
  1903. std::string const& lang,
  1904. const std::string& config)
  1905. {
  1906. int targetType = target->GetType();
  1907. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  1908. (targetType == cmStateEnums::MODULE_LIBRARY));
  1909. if (this->GetShouldUseOldFlags(shared, lang)) {
  1910. this->AddSharedFlags(flags, lang, shared);
  1911. } else {
  1912. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1913. if (target->GetPropertyAsBool("POSITION_INDEPENDENT_CODE")) {
  1914. this->AddPositionIndependentFlags(flags, lang, targetType);
  1915. }
  1916. return;
  1917. }
  1918. if (target->GetLinkInterfaceDependentBoolProperty(
  1919. "POSITION_INDEPENDENT_CODE", config)) {
  1920. this->AddPositionIndependentFlags(flags, lang, targetType);
  1921. }
  1922. if (shared) {
  1923. this->AppendFeatureOptions(flags, lang, "DLL");
  1924. }
  1925. }
  1926. }
  1927. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  1928. const std::string& lang) const
  1929. {
  1930. std::string originalFlags =
  1931. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  1932. if (shared) {
  1933. std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  1934. std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
  1935. if (flags != originalFlags) {
  1936. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  1937. case cmPolicies::WARN: {
  1938. std::ostringstream e;
  1939. e << "Variable " << flagsVar
  1940. << " has been modified. CMake "
  1941. "will ignore the POSITION_INDEPENDENT_CODE target property for "
  1942. "shared libraries and will use the "
  1943. << flagsVar
  1944. << " variable "
  1945. "instead. This may cause errors if the original content of "
  1946. << flagsVar << " was removed.\n"
  1947. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  1948. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  1949. CM_FALLTHROUGH;
  1950. }
  1951. case cmPolicies::OLD:
  1952. return true;
  1953. case cmPolicies::REQUIRED_IF_USED:
  1954. case cmPolicies::REQUIRED_ALWAYS:
  1955. case cmPolicies::NEW:
  1956. return false;
  1957. }
  1958. }
  1959. }
  1960. return false;
  1961. }
  1962. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  1963. std::string const& lang,
  1964. int targetType)
  1965. {
  1966. std::string picFlags;
  1967. if (targetType == cmStateEnums::EXECUTABLE) {
  1968. picFlags = this->Makefile->GetSafeDefinition(
  1969. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
  1970. }
  1971. if (picFlags.empty()) {
  1972. picFlags = this->Makefile->GetSafeDefinition(
  1973. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
  1974. }
  1975. if (!picFlags.empty()) {
  1976. std::vector<std::string> options = cmExpandedList(picFlags);
  1977. for (std::string const& o : options) {
  1978. this->AppendFlagEscape(flags, o);
  1979. }
  1980. }
  1981. }
  1982. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  1983. const std::string& var,
  1984. const std::string& config)
  1985. {
  1986. // Add the flags from the variable itself.
  1987. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
  1988. // Add the flags from the build-type specific variable.
  1989. if (!config.empty()) {
  1990. const std::string flagsVar =
  1991. cmStrCat(var, '_', cmSystemTools::UpperCase(config));
  1992. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
  1993. }
  1994. }
  1995. void cmLocalGenerator::AppendFlags(std::string& flags,
  1996. const std::string& newFlags) const
  1997. {
  1998. if (!newFlags.empty()) {
  1999. if (!flags.empty()) {
  2000. flags += " ";
  2001. }
  2002. flags += newFlags;
  2003. }
  2004. }
  2005. void cmLocalGenerator::AppendFlags(
  2006. std::string& flags, const std::vector<BT<std::string>>& newFlags) const
  2007. {
  2008. for (BT<std::string> const& flag : newFlags) {
  2009. this->AppendFlags(flags, flag.Value);
  2010. }
  2011. }
  2012. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  2013. const std::string& rawFlag) const
  2014. {
  2015. this->AppendFlags(flags, this->EscapeForShell(rawFlag));
  2016. }
  2017. void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target,
  2018. const std::string& config)
  2019. {
  2020. const std::string lang = target->GetLinkerLanguage(config);
  2021. const std::string buildType = cmSystemTools::UpperCase(config);
  2022. const std::string pchSource = target->GetPchSource(config, lang);
  2023. const std::string pchHeader = target->GetPchHeader(config, lang);
  2024. if (pchSource.empty() || pchHeader.empty()) {
  2025. return;
  2026. }
  2027. const std::string createOptVar =
  2028. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_CREATE_PCH");
  2029. std::string createOptionList =
  2030. this->Makefile->GetSafeDefinition(createOptVar);
  2031. const std::string useOptVar =
  2032. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_USE_PCH");
  2033. std::string useOptionList = this->Makefile->GetSafeDefinition(useOptVar);
  2034. const std::string pchExtension =
  2035. this->Makefile->GetSafeDefinition("CMAKE_PCH_EXTENSION");
  2036. if (createOptionList.empty() || useOptionList.empty() ||
  2037. pchExtension.empty()) {
  2038. return;
  2039. }
  2040. const char* pchReuseFrom =
  2041. target->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2042. auto pch_sf = this->Makefile->GetOrCreateSource(
  2043. pchSource, false, cmSourceFileLocationKind::Known);
  2044. std::string pchFile = pchHeader;
  2045. if (!this->GetGlobalGenerator()->IsXcode()) {
  2046. if (!pchReuseFrom) {
  2047. target->AddSource(pchSource, true);
  2048. }
  2049. // Exclude the pch files from linking
  2050. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2051. auto replaceExtension = [](const std::string& str,
  2052. const std::string& ext) -> std::string {
  2053. auto dot_pos = str.rfind('.');
  2054. std::string result;
  2055. if (dot_pos != std::string::npos) {
  2056. result = str.substr(0, dot_pos);
  2057. }
  2058. result += ext;
  2059. return result;
  2060. };
  2061. if (!pchReuseFrom) {
  2062. std::string pchSourceObj = target->GetPchFileObject(config, lang);
  2063. pchFile = replaceExtension(pchSourceObj, pchExtension);
  2064. pch_sf->SetProperty("OBJECT_OUTPUTS", pchFile.c_str());
  2065. } else {
  2066. auto reuseTarget =
  2067. this->GlobalGenerator->FindGeneratorTarget(pchReuseFrom);
  2068. if (this->Makefile->IsOn("CMAKE_PCH_COPY_COMPILE_PDB")) {
  2069. const std::string pdb_prefix =
  2070. this->GetGlobalGenerator()->IsMultiConfig()
  2071. ? cmStrCat(this->GlobalGenerator->GetCMakeCFGIntDir(), "/")
  2072. : "";
  2073. const std::string target_compile_pdb_dir =
  2074. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  2075. "/", target->GetName(), ".dir/");
  2076. const std::string copy_script =
  2077. cmStrCat(target_compile_pdb_dir, "copy_idb_pdb.cmake");
  2078. cmGeneratedFileStream file(copy_script);
  2079. file << "# CMake generated file\n";
  2080. for (auto extension : { ".pdb", ".idb" }) {
  2081. const std::string from_file = cmStrCat(
  2082. reuseTarget->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  2083. "/", pchReuseFrom, ".dir/${PDB_PREFIX}", pchReuseFrom,
  2084. extension);
  2085. const std::string to_dir = cmStrCat(
  2086. target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2087. target->GetName(), ".dir/${PDB_PREFIX}");
  2088. file << "if (EXISTS \"" << from_file << "\")\n";
  2089. file << " file(COPY \"" << from_file << "\""
  2090. << " DESTINATION \"" << to_dir << "\")\n";
  2091. file << "endif()\n";
  2092. }
  2093. cmCustomCommandLines commandLines;
  2094. cmCustomCommandLine currentLine;
  2095. currentLine.push_back(cmSystemTools::GetCMakeCommand());
  2096. currentLine.push_back(cmStrCat("-DPDB_PREFIX=", pdb_prefix));
  2097. currentLine.push_back("-P");
  2098. currentLine.push_back(copy_script);
  2099. commandLines.push_back(std::move(currentLine));
  2100. const std::string no_main_dependency;
  2101. const std::vector<std::string> no_deps;
  2102. const char* no_message = "";
  2103. const char* no_current_dir = nullptr;
  2104. std::vector<std::string> no_byproducts;
  2105. std::vector<std::string> outputs;
  2106. outputs.push_back(cmStrCat(target_compile_pdb_dir, pdb_prefix,
  2107. pchReuseFrom, ".pdb"));
  2108. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2109. this->Makefile->AddCustomCommandToTarget(
  2110. target->GetName(), outputs, no_deps, commandLines,
  2111. cmTarget::PRE_BUILD, no_message, no_current_dir);
  2112. } else {
  2113. cmImplicitDependsList no_implicit_depends;
  2114. cmSourceFile* copy_rule = this->Makefile->AddCustomCommandToOutput(
  2115. outputs, no_byproducts, no_deps, no_main_dependency,
  2116. no_implicit_depends, commandLines, no_message, no_current_dir);
  2117. if (copy_rule) {
  2118. target->AddSource(copy_rule->ResolveFullPath());
  2119. }
  2120. }
  2121. target->Target->SetProperty("COMPILE_PDB_OUTPUT_DIRECTORY",
  2122. target_compile_pdb_dir.c_str());
  2123. }
  2124. std::string pchSourceObj = reuseTarget->GetPchFileObject(config, lang);
  2125. // Link to the pch object file
  2126. target->Target->SetProperty(
  2127. "LINK_FLAGS",
  2128. this->ConvertToOutputFormat(pchSourceObj, SHELL).c_str());
  2129. pchFile = replaceExtension(pchSourceObj, pchExtension);
  2130. }
  2131. } else {
  2132. pchFile += pchExtension;
  2133. pch_sf->SetProperty("PCH_EXTENSION", pchExtension.c_str());
  2134. }
  2135. // Add pchHeader to source files, which will
  2136. // be grouped as "Precompile Header File"
  2137. auto pchHeader_sf = this->Makefile->GetOrCreateSource(
  2138. pchHeader, false, cmSourceFileLocationKind::Known);
  2139. std::string err;
  2140. pchHeader_sf->ResolveFullPath(&err);
  2141. target->AddSource(pchHeader);
  2142. for (auto& str : { std::ref(useOptionList), std::ref(createOptionList) }) {
  2143. cmSystemTools::ReplaceString(str, "<PCH_HEADER>", pchHeader);
  2144. cmSystemTools::ReplaceString(str, "<PCH_FILE>", pchFile);
  2145. }
  2146. }
  2147. pch_sf->SetProperty("COMPILE_OPTIONS", createOptionList.c_str());
  2148. std::vector<cmSourceFile*> sources;
  2149. target->GetSourceFiles(sources, buildType);
  2150. for (cmSourceFile* sf : sources) {
  2151. if (pch_sf == sf || sf->GetLanguage() != lang) {
  2152. continue;
  2153. }
  2154. if (sf->GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS")) {
  2155. if (this->GetGlobalGenerator()->IsXcode()) {
  2156. sf->SetProperty("COMPILE_DEFINITIONS",
  2157. "CMAKE_SKIP_PRECOMPILE_HEADERS");
  2158. }
  2159. continue;
  2160. }
  2161. if (!this->GetGlobalGenerator()->IsXcode()) {
  2162. sf->AppendProperty("OBJECT_DEPENDS", pchFile.c_str());
  2163. sf->AppendProperty("OBJECT_DEPENDS", pchHeader.c_str());
  2164. sf->SetProperty("COMPILE_OPTIONS", useOptionList.c_str());
  2165. }
  2166. }
  2167. }
  2168. void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target,
  2169. const std::string& config)
  2170. {
  2171. if (!target->GetPropertyAsBool("UNITY_BUILD")) {
  2172. return;
  2173. }
  2174. const std::string buildType = cmSystemTools::UpperCase(config);
  2175. std::string filename_base =
  2176. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  2177. target->GetName(), ".dir/Unity/");
  2178. std::vector<cmSourceFile*> sources;
  2179. target->GetSourceFiles(sources, buildType);
  2180. auto batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
  2181. const size_t unityBatchSize =
  2182. static_cast<size_t>(std::atoi(batchSizeString));
  2183. auto beforeInclude = target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
  2184. auto afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
  2185. for (std::string lang : { "C", "CXX" }) {
  2186. std::vector<cmSourceFile*> filtered_sources;
  2187. std::copy_if(sources.begin(), sources.end(),
  2188. std::back_inserter(filtered_sources), [&](cmSourceFile* sf) {
  2189. return sf->GetLanguage() == lang &&
  2190. !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
  2191. !sf->GetPropertyAsBool("GENERATED") &&
  2192. !sf->GetProperty("COMPILE_OPTIONS") &&
  2193. !sf->GetProperty("COMPILE_DEFINITIONS") &&
  2194. !sf->GetProperty("COMPILE_FLAGS") &&
  2195. !sf->GetProperty("INCLUDE_DIRECTORIES");
  2196. });
  2197. size_t batchSize = unityBatchSize;
  2198. if (unityBatchSize == 0) {
  2199. batchSize = filtered_sources.size();
  2200. }
  2201. for (size_t itemsLeft = filtered_sources.size(), chunk = batchSize,
  2202. batch = 0;
  2203. itemsLeft > 0; itemsLeft -= chunk, ++batch) {
  2204. chunk = std::min(itemsLeft, batchSize);
  2205. std::string filename = cmStrCat(filename_base, "unity_", batch,
  2206. (lang == "C") ? ".c" : ".cxx");
  2207. const std::string filename_tmp = cmStrCat(filename, ".tmp");
  2208. {
  2209. size_t begin = batch * batchSize;
  2210. size_t end = begin + chunk;
  2211. cmGeneratedFileStream file(
  2212. filename_tmp, false,
  2213. this->GetGlobalGenerator()->GetMakefileEncoding());
  2214. file << "/* generated by CMake */\n\n";
  2215. for (; begin != end; ++begin) {
  2216. cmSourceFile* sf = filtered_sources[begin];
  2217. // Only in Visual Studio generator we keep the source files
  2218. // for explicit processing. For the rest the source files will
  2219. // not be included in the project.
  2220. if (!this->GetGlobalGenerator()->IsMultiConfig() ||
  2221. this->GetGlobalGenerator()->IsXcode()) {
  2222. sf->SetProperty("HEADER_FILE_ONLY", "ON");
  2223. }
  2224. sf->SetProperty("UNITY_SOURCE_FILE", filename.c_str());
  2225. if (beforeInclude) {
  2226. file << beforeInclude << "\n";
  2227. }
  2228. file << "#include \"" << sf->GetFullPath() << "\"\n";
  2229. if (afterInclude) {
  2230. file << afterInclude << "\n";
  2231. }
  2232. }
  2233. }
  2234. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2235. target->AddSource(filename, true);
  2236. auto unity = this->Makefile->GetOrCreateSource(filename);
  2237. unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
  2238. unity->SetProperty("UNITY_SOURCE_FILE", filename.c_str());
  2239. }
  2240. }
  2241. }
  2242. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  2243. cmGeneratorTarget* target,
  2244. const std::string& config,
  2245. const std::string& lang)
  2246. {
  2247. if (!target->IsIPOEnabled(lang, config)) {
  2248. return;
  2249. }
  2250. switch (target->GetType()) {
  2251. case cmStateEnums::EXECUTABLE:
  2252. case cmStateEnums::SHARED_LIBRARY:
  2253. case cmStateEnums::MODULE_LIBRARY:
  2254. break;
  2255. default:
  2256. return;
  2257. }
  2258. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  2259. const char* rawFlagsList = this->Makefile->GetDefinition(name);
  2260. if (rawFlagsList == nullptr) {
  2261. return;
  2262. }
  2263. std::vector<std::string> flagsList = cmExpandedList(rawFlagsList);
  2264. for (std::string const& o : flagsList) {
  2265. this->AppendFlagEscape(flags, o);
  2266. }
  2267. }
  2268. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  2269. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  2270. const std::string& lang)
  2271. {
  2272. // For now, only EXECUTABLE is concerned
  2273. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  2274. return;
  2275. }
  2276. const char* PICValue = target->GetLinkPIEProperty(config);
  2277. if (PICValue == nullptr) {
  2278. // POSITION_INDEPENDENT_CODE is not set
  2279. return;
  2280. }
  2281. const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
  2282. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  2283. if (cmIsOff(this->Makefile->GetDefinition(supported))) {
  2284. return;
  2285. }
  2286. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  2287. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  2288. if (pieFlags.empty()) {
  2289. return;
  2290. }
  2291. std::vector<std::string> flagsList = cmExpandedList(pieFlags);
  2292. for (const auto& flag : flagsList) {
  2293. this->AppendFlagEscape(flags, flag);
  2294. }
  2295. }
  2296. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  2297. const char* options_list,
  2298. const char* regex) const
  2299. {
  2300. // Short-circuit if there are no options.
  2301. if (!options_list) {
  2302. return;
  2303. }
  2304. // Expand the list of options.
  2305. std::vector<std::string> options_vec = cmExpandedList(options_list);
  2306. this->AppendCompileOptions(options, options_vec, regex);
  2307. }
  2308. void cmLocalGenerator::AppendCompileOptions(
  2309. std::string& options, const std::vector<std::string>& options_vec,
  2310. const char* regex) const
  2311. {
  2312. if (regex != nullptr) {
  2313. // Filter flags upon specified reges.
  2314. cmsys::RegularExpression r(regex);
  2315. for (std::string const& opt : options_vec) {
  2316. if (r.find(opt)) {
  2317. this->AppendFlagEscape(options, opt);
  2318. }
  2319. }
  2320. } else {
  2321. for (std::string const& opt : options_vec) {
  2322. this->AppendFlagEscape(options, opt);
  2323. }
  2324. }
  2325. }
  2326. void cmLocalGenerator::AppendCompileOptions(
  2327. std::vector<BT<std::string>>& options,
  2328. const std::vector<BT<std::string>>& options_vec, const char* regex) const
  2329. {
  2330. if (regex != nullptr) {
  2331. // Filter flags upon specified regular expressions.
  2332. cmsys::RegularExpression r(regex);
  2333. for (BT<std::string> const& opt : options_vec) {
  2334. if (r.find(opt.Value)) {
  2335. std::string flag;
  2336. this->AppendFlagEscape(flag, opt.Value);
  2337. options.emplace_back(std::move(flag), opt.Backtrace);
  2338. }
  2339. }
  2340. } else {
  2341. for (BT<std::string> const& opt : options_vec) {
  2342. std::string flag;
  2343. this->AppendFlagEscape(flag, opt.Value);
  2344. options.emplace_back(std::move(flag), opt.Backtrace);
  2345. }
  2346. }
  2347. }
  2348. void cmLocalGenerator::AppendIncludeDirectories(
  2349. std::vector<std::string>& includes, const char* includes_list,
  2350. const cmSourceFile& sourceFile) const
  2351. {
  2352. // Short-circuit if there are no includes.
  2353. if (!includes_list) {
  2354. return;
  2355. }
  2356. // Expand the list of includes.
  2357. std::vector<std::string> includes_vec = cmExpandedList(includes_list);
  2358. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  2359. }
  2360. void cmLocalGenerator::AppendIncludeDirectories(
  2361. std::vector<std::string>& includes,
  2362. const std::vector<std::string>& includes_vec,
  2363. const cmSourceFile& sourceFile) const
  2364. {
  2365. std::unordered_set<std::string> uniqueIncludes;
  2366. for (const std::string& include : includes_vec) {
  2367. if (!cmSystemTools::FileIsFullPath(include)) {
  2368. std::ostringstream e;
  2369. e << "Found relative path while evaluating include directories of "
  2370. "\""
  2371. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  2372. << "\"\n";
  2373. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2374. return;
  2375. }
  2376. std::string inc = include;
  2377. if (!cmIsOff(inc)) {
  2378. cmSystemTools::ConvertToUnixSlashes(inc);
  2379. }
  2380. if (uniqueIncludes.insert(inc).second) {
  2381. includes.push_back(std::move(inc));
  2382. }
  2383. }
  2384. }
  2385. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  2386. std::string const& defines_list) const
  2387. {
  2388. std::set<BT<std::string>> tmp;
  2389. this->AppendDefines(tmp, ExpandListWithBacktrace(defines_list));
  2390. for (BT<std::string> const& i : tmp) {
  2391. defines.emplace(i.Value);
  2392. }
  2393. }
  2394. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  2395. std::string const& defines_list) const
  2396. {
  2397. // Short-circuit if there are no definitions.
  2398. if (defines_list.empty()) {
  2399. return;
  2400. }
  2401. // Expand the list of definitions.
  2402. this->AppendDefines(defines, ExpandListWithBacktrace(defines_list));
  2403. }
  2404. void cmLocalGenerator::AppendDefines(
  2405. std::set<BT<std::string>>& defines,
  2406. const std::vector<BT<std::string>>& defines_vec) const
  2407. {
  2408. for (BT<std::string> const& d : defines_vec) {
  2409. // Skip unsupported definitions.
  2410. if (!this->CheckDefinition(d.Value)) {
  2411. continue;
  2412. }
  2413. defines.insert(d);
  2414. }
  2415. }
  2416. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  2417. std::string& definesString,
  2418. const std::string& lang)
  2419. {
  2420. // Lookup the define flag for the current language.
  2421. std::string dflag = "-D";
  2422. if (!lang.empty()) {
  2423. const char* df =
  2424. this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
  2425. if (df && *df) {
  2426. dflag = df;
  2427. }
  2428. }
  2429. const char* itemSeparator = definesString.empty() ? "" : " ";
  2430. for (std::string const& define : defines) {
  2431. // Append the definition with proper escaping.
  2432. std::string def = dflag;
  2433. if (this->GetState()->UseWatcomWMake()) {
  2434. // The Watcom compiler does its own command line parsing instead
  2435. // of using the windows shell rules. Definitions are one of
  2436. // -DNAME
  2437. // -DNAME=<cpp-token>
  2438. // -DNAME="c-string with spaces and other characters(?@#$)"
  2439. //
  2440. // Watcom will properly parse each of these cases from the
  2441. // command line without any escapes. However we still have to
  2442. // get the '$' and '#' characters through WMake as '$$' and
  2443. // '$#'.
  2444. for (const char* c = define.c_str(); *c; ++c) {
  2445. if (*c == '$' || *c == '#') {
  2446. def += '$';
  2447. }
  2448. def += *c;
  2449. }
  2450. } else {
  2451. // Make the definition appear properly on the command line. Use
  2452. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  2453. std::string::size_type eq = define.find('=');
  2454. def += define.substr(0, eq);
  2455. if (eq != std::string::npos) {
  2456. def += "=";
  2457. def += this->EscapeForShell(define.substr(eq + 1), true);
  2458. }
  2459. }
  2460. definesString += itemSeparator;
  2461. itemSeparator = " ";
  2462. definesString += def;
  2463. }
  2464. }
  2465. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  2466. const std::string& lang,
  2467. const char* feature)
  2468. {
  2469. const char* optionList = this->Makefile->GetDefinition(
  2470. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
  2471. if (optionList != nullptr) {
  2472. std::vector<std::string> options = cmExpandedList(optionList);
  2473. for (std::string const& o : options) {
  2474. this->AppendFlagEscape(flags, o);
  2475. }
  2476. }
  2477. }
  2478. const char* cmLocalGenerator::GetFeature(const std::string& feature,
  2479. const std::string& config)
  2480. {
  2481. std::string featureName = feature;
  2482. // TODO: Define accumulation policy for features (prepend, append, replace).
  2483. // Currently we always replace.
  2484. if (!config.empty()) {
  2485. featureName += "_";
  2486. featureName += cmSystemTools::UpperCase(config);
  2487. }
  2488. cmStateSnapshot snp = this->StateSnapshot;
  2489. while (snp.IsValid()) {
  2490. if (const char* value = snp.GetDirectory().GetProperty(featureName)) {
  2491. return value;
  2492. }
  2493. snp = snp.GetBuildsystemDirectoryParent();
  2494. }
  2495. return nullptr;
  2496. }
  2497. std::string cmLocalGenerator::GetProjectName() const
  2498. {
  2499. return this->StateSnapshot.GetProjectName();
  2500. }
  2501. std::string cmLocalGenerator::ConstructComment(
  2502. cmCustomCommandGenerator const& ccg, const char* default_comment)
  2503. {
  2504. // Check for a comment provided with the command.
  2505. if (ccg.GetComment()) {
  2506. return ccg.GetComment();
  2507. }
  2508. // Construct a reasonable default comment if possible.
  2509. if (!ccg.GetOutputs().empty()) {
  2510. std::string comment;
  2511. comment = "Generating ";
  2512. const char* sep = "";
  2513. std::string currentBinaryDir = this->GetCurrentBinaryDirectory();
  2514. for (std::string const& o : ccg.GetOutputs()) {
  2515. comment += sep;
  2516. comment += this->MaybeConvertToRelativePath(currentBinaryDir, o);
  2517. sep = ", ";
  2518. }
  2519. return comment;
  2520. }
  2521. // Otherwise use the provided default.
  2522. return default_comment;
  2523. }
  2524. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  2525. {
  2526. public:
  2527. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  2528. const char* dest, bool implib)
  2529. : cmInstallTargetGenerator(
  2530. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  2531. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  2532. false)
  2533. {
  2534. this->Compute(lg);
  2535. }
  2536. };
  2537. void cmLocalGenerator::GenerateTargetInstallRules(
  2538. std::ostream& os, const std::string& config,
  2539. std::vector<std::string> const& configurationTypes)
  2540. {
  2541. // Convert the old-style install specification from each target to
  2542. // an install generator and run it.
  2543. const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
  2544. for (cmGeneratorTarget* l : tgts) {
  2545. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2546. continue;
  2547. }
  2548. // Include the user-specified pre-install script for this target.
  2549. if (const char* preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  2550. cmInstallScriptGenerator g(preinstall, false, nullptr, false);
  2551. g.Generate(os, config, configurationTypes);
  2552. }
  2553. // Install this target if a destination is given.
  2554. if (!l->Target->GetInstallPath().empty()) {
  2555. // Compute the full install destination. Note that converting
  2556. // to unix slashes also removes any trailing slash.
  2557. // We also skip over the leading slash given by the user.
  2558. std::string destination = l->Target->GetInstallPath().substr(1);
  2559. cmSystemTools::ConvertToUnixSlashes(destination);
  2560. if (destination.empty()) {
  2561. destination = ".";
  2562. }
  2563. // Generate the proper install generator for this target type.
  2564. switch (l->GetType()) {
  2565. case cmStateEnums::EXECUTABLE:
  2566. case cmStateEnums::STATIC_LIBRARY:
  2567. case cmStateEnums::MODULE_LIBRARY: {
  2568. // Use a target install generator.
  2569. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2570. destination.c_str(), false);
  2571. g.Generate(os, config, configurationTypes);
  2572. } break;
  2573. case cmStateEnums::SHARED_LIBRARY: {
  2574. #if defined(_WIN32) || defined(__CYGWIN__)
  2575. // Special code to handle DLL. Install the import library
  2576. // to the normal destination and the DLL to the runtime
  2577. // destination.
  2578. cmInstallTargetGeneratorLocal g1(this, l->GetName(),
  2579. destination.c_str(), true);
  2580. g1.Generate(os, config, configurationTypes);
  2581. // We also skip over the leading slash given by the user.
  2582. destination = l->Target->GetRuntimeInstallPath().substr(1);
  2583. cmSystemTools::ConvertToUnixSlashes(destination);
  2584. cmInstallTargetGeneratorLocal g2(this, l->GetName(),
  2585. destination.c_str(), false);
  2586. g2.Generate(os, config, configurationTypes);
  2587. #else
  2588. // Use a target install generator.
  2589. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2590. destination.c_str(), false);
  2591. g.Generate(os, config, configurationTypes);
  2592. #endif
  2593. } break;
  2594. default:
  2595. break;
  2596. }
  2597. }
  2598. // Include the user-specified post-install script for this target.
  2599. if (const char* postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  2600. cmInstallScriptGenerator g(postinstall, false, nullptr, false);
  2601. g.Generate(os, config, configurationTypes);
  2602. }
  2603. }
  2604. }
  2605. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2606. static bool cmLocalGeneratorShortenObjectName(std::string& objName,
  2607. std::string::size_type max_len)
  2608. {
  2609. // Replace the beginning of the path portion of the object name with
  2610. // its own md5 sum.
  2611. std::string::size_type pos =
  2612. objName.find('/', objName.size() - max_len + 32);
  2613. if (pos != std::string::npos) {
  2614. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  2615. std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
  2616. cm::string_view(objName).substr(pos));
  2617. objName = md5name;
  2618. // The object name is now short enough.
  2619. return true;
  2620. }
  2621. // The object name could not be shortened enough.
  2622. return false;
  2623. }
  2624. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  2625. std::string::size_type dir_len,
  2626. std::string::size_type max_total_len)
  2627. {
  2628. // Enforce the maximum file name length if possible.
  2629. std::string::size_type max_obj_len = max_total_len;
  2630. if (dir_len < max_total_len) {
  2631. max_obj_len = max_total_len - dir_len;
  2632. if (objName.size() > max_obj_len) {
  2633. // The current object file name is too long. Try to shorten it.
  2634. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  2635. }
  2636. // The object file name is short enough.
  2637. return true;
  2638. }
  2639. // The build directory in which the object will be stored is
  2640. // already too deep.
  2641. return false;
  2642. }
  2643. #endif
  2644. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  2645. const std::string& sin, std::string const& dir_max)
  2646. {
  2647. // Look for an existing mapped name for this object file.
  2648. auto it = this->UniqueObjectNamesMap.find(sin);
  2649. // If no entry exists create one.
  2650. if (it == this->UniqueObjectNamesMap.end()) {
  2651. // Start with the original name.
  2652. std::string ssin = sin;
  2653. // Avoid full paths by removing leading slashes.
  2654. ssin.erase(0, ssin.find_first_not_of('/'));
  2655. // Avoid full paths by removing colons.
  2656. std::replace(ssin.begin(), ssin.end(), ':', '_');
  2657. // Avoid relative paths that go up the tree.
  2658. cmSystemTools::ReplaceString(ssin, "../", "__/");
  2659. // Avoid spaces.
  2660. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  2661. // Mangle the name if necessary.
  2662. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  2663. bool done;
  2664. int cc = 0;
  2665. char rpstr[100];
  2666. sprintf(rpstr, "_p_");
  2667. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  2668. std::string sssin = sin;
  2669. do {
  2670. done = true;
  2671. for (it = this->UniqueObjectNamesMap.begin();
  2672. it != this->UniqueObjectNamesMap.end(); ++it) {
  2673. if (it->second == ssin) {
  2674. done = false;
  2675. }
  2676. }
  2677. if (done) {
  2678. break;
  2679. }
  2680. sssin = ssin;
  2681. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  2682. sprintf(rpstr, "_p%d_", cc++);
  2683. } while (!done);
  2684. }
  2685. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2686. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  2687. this->ObjectPathMax)) {
  2688. // Warn if this is the first time the path has been seen.
  2689. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  2690. std::ostringstream m;
  2691. /* clang-format off */
  2692. m << "The object file directory\n"
  2693. << " " << dir_max << "\n"
  2694. << "has " << dir_max.size() << " characters. "
  2695. << "The maximum full path to an object file is "
  2696. << this->ObjectPathMax << " characters "
  2697. << "(see CMAKE_OBJECT_PATH_MAX). "
  2698. << "Object file\n"
  2699. << " " << ssin << "\n"
  2700. << "cannot be safely placed under this directory. "
  2701. << "The build may not work correctly.";
  2702. /* clang-format on */
  2703. this->IssueMessage(MessageType::WARNING, m.str());
  2704. }
  2705. }
  2706. #else
  2707. (void)dir_max;
  2708. #endif
  2709. // Insert the newly mapped object file name.
  2710. std::map<std::string, std::string>::value_type e(sin, ssin);
  2711. it = this->UniqueObjectNamesMap.insert(e).first;
  2712. }
  2713. // Return the map entry.
  2714. return it->second;
  2715. }
  2716. void cmLocalGenerator::ComputeObjectFilenames(
  2717. std::map<cmSourceFile const*, std::string>& /*unused*/,
  2718. cmGeneratorTarget const* /*unused*/)
  2719. {
  2720. }
  2721. bool cmLocalGenerator::IsWindowsShell() const
  2722. {
  2723. return this->GetState()->UseWindowsShell();
  2724. }
  2725. bool cmLocalGenerator::IsWatcomWMake() const
  2726. {
  2727. return this->GetState()->UseWatcomWMake();
  2728. }
  2729. bool cmLocalGenerator::IsMinGWMake() const
  2730. {
  2731. return this->GetState()->UseMinGWMake();
  2732. }
  2733. bool cmLocalGenerator::IsNMake() const
  2734. {
  2735. return this->GetState()->UseNMake();
  2736. }
  2737. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  2738. const cmSourceFile& source, std::string const& dir_max,
  2739. bool* hasSourceExtension, char const* customOutputExtension)
  2740. {
  2741. // Construct the object file name using the full path to the source
  2742. // file which is its only unique identification.
  2743. std::string const& fullPath = source.GetFullPath();
  2744. // Try referencing the source relative to the source tree.
  2745. std::string relFromSource = this->MaybeConvertToRelativePath(
  2746. this->GetCurrentSourceDirectory(), fullPath);
  2747. assert(!relFromSource.empty());
  2748. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  2749. bool subSource = relSource && relFromSource[0] != '.';
  2750. // Try referencing the source relative to the binary tree.
  2751. std::string relFromBinary = this->MaybeConvertToRelativePath(
  2752. this->GetCurrentBinaryDirectory(), fullPath);
  2753. assert(!relFromBinary.empty());
  2754. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  2755. bool subBinary = relBinary && relFromBinary[0] != '.';
  2756. // Select a nice-looking reference to the source file to construct
  2757. // the object file name.
  2758. std::string objectName;
  2759. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  2760. objectName = relFromSource;
  2761. } else if ((relBinary && !relSource) || (subBinary && !subSource)) {
  2762. objectName = relFromBinary;
  2763. } else if (relFromBinary.length() < relFromSource.length()) {
  2764. objectName = relFromBinary;
  2765. } else {
  2766. objectName = relFromSource;
  2767. }
  2768. // if it is still a full path check for the try compile case
  2769. // try compile never have in source sources, and should not
  2770. // have conflicting source file names in the same target
  2771. if (cmSystemTools::FileIsFullPath(objectName)) {
  2772. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  2773. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  2774. }
  2775. }
  2776. // Replace the original source file extension with the object file
  2777. // extension.
  2778. bool keptSourceExtension = true;
  2779. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  2780. // Decide whether this language wants to replace the source
  2781. // extension with the object extension. For CMake 2.4
  2782. // compatibility do this by default.
  2783. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  2784. if (!replaceExt) {
  2785. std::string lang = source.GetLanguage();
  2786. if (!lang.empty()) {
  2787. replaceExt = this->Makefile->IsOn(
  2788. cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
  2789. }
  2790. }
  2791. const char* pchExtension = source.GetProperty("PCH_EXTENSION");
  2792. if (pchExtension) {
  2793. customOutputExtension = pchExtension;
  2794. }
  2795. // Remove the source extension if it is to be replaced.
  2796. if (replaceExt || customOutputExtension) {
  2797. keptSourceExtension = false;
  2798. std::string::size_type dot_pos = objectName.rfind('.');
  2799. if (dot_pos != std::string::npos) {
  2800. objectName = objectName.substr(0, dot_pos);
  2801. }
  2802. }
  2803. // Store the new extension.
  2804. if (customOutputExtension) {
  2805. objectName += customOutputExtension;
  2806. } else {
  2807. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  2808. }
  2809. }
  2810. if (hasSourceExtension) {
  2811. *hasSourceExtension = keptSourceExtension;
  2812. }
  2813. // Convert to a safe name.
  2814. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  2815. }
  2816. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  2817. {
  2818. return source.GetLanguage();
  2819. }
  2820. cmake* cmLocalGenerator::GetCMakeInstance() const
  2821. {
  2822. return this->GlobalGenerator->GetCMakeInstance();
  2823. }
  2824. std::string const& cmLocalGenerator::GetSourceDirectory() const
  2825. {
  2826. return this->GetCMakeInstance()->GetHomeDirectory();
  2827. }
  2828. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  2829. {
  2830. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  2831. }
  2832. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  2833. {
  2834. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  2835. }
  2836. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  2837. {
  2838. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  2839. }
  2840. std::string cmLocalGenerator::MaybeConvertToRelativePath(
  2841. std::string const& local_path, std::string const& remote_path) const
  2842. {
  2843. return this->StateSnapshot.GetDirectory().ConvertToRelPathIfNotContained(
  2844. local_path, remote_path);
  2845. }
  2846. std::string cmLocalGenerator::GetTargetDirectory(
  2847. const cmGeneratorTarget* /*unused*/) const
  2848. {
  2849. cmSystemTools::Error("GetTargetDirectory"
  2850. " called on cmLocalGenerator");
  2851. return "";
  2852. }
  2853. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  2854. {
  2855. // The computed version may change until the project is fully
  2856. // configured.
  2857. if (!this->BackwardsCompatibilityFinal) {
  2858. unsigned int major = 0;
  2859. unsigned int minor = 0;
  2860. unsigned int patch = 0;
  2861. if (const char* value =
  2862. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  2863. switch (sscanf(value, "%u.%u.%u", &major, &minor, &patch)) {
  2864. case 2:
  2865. patch = 0;
  2866. break;
  2867. case 1:
  2868. minor = 0;
  2869. patch = 0;
  2870. break;
  2871. default:
  2872. break;
  2873. }
  2874. }
  2875. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  2876. this->BackwardsCompatibilityFinal = true;
  2877. }
  2878. return this->BackwardsCompatibility;
  2879. }
  2880. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  2881. {
  2882. // Check the policy to decide whether to pay attention to this
  2883. // variable.
  2884. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  2885. case cmPolicies::WARN:
  2886. // WARN is just OLD without warning because user code does not
  2887. // always affect whether this check is done.
  2888. case cmPolicies::OLD:
  2889. // Old behavior is to check the variable.
  2890. break;
  2891. case cmPolicies::NEW:
  2892. // New behavior is to ignore the variable.
  2893. return false;
  2894. case cmPolicies::REQUIRED_IF_USED:
  2895. case cmPolicies::REQUIRED_ALWAYS:
  2896. // This will never be the case because the only way to require
  2897. // the setting is to require the user to specify version policy
  2898. // 2.6 or higher. Once we add that requirement then this whole
  2899. // method can be removed anyway.
  2900. return false;
  2901. }
  2902. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  2903. // equal to or lower than the given version.
  2904. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  2905. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  2906. }
  2907. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  2908. cmPolicies::PolicyID id) const
  2909. {
  2910. return this->Makefile->GetPolicyStatus(id);
  2911. }
  2912. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  2913. {
  2914. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  2915. std::string::size_type pos = define.find_first_of("(=");
  2916. if (pos != std::string::npos) {
  2917. if (define[pos] == '(') {
  2918. std::ostringstream e;
  2919. /* clang-format off */
  2920. e << "WARNING: Function-style preprocessor definitions may not be "
  2921. << "passed on the compiler command line because many compilers "
  2922. << "do not support it.\n"
  2923. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2924. << "Consider defining the macro in a (configured) header file.\n";
  2925. /* clang-format on */
  2926. cmSystemTools::Message(e.str());
  2927. return false;
  2928. }
  2929. }
  2930. // Many compilers do not support # in the value so we disable it.
  2931. if (define.find_first_of('#') != std::string::npos) {
  2932. std::ostringstream e;
  2933. /* clang-format off */
  2934. e << "WARNING: Preprocessor definitions containing '#' may not be "
  2935. << "passed on the compiler command line because many compilers "
  2936. << "do not support it.\n"
  2937. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2938. << "Consider defining the macro in a (configured) header file.\n";
  2939. /* clang-format on */
  2940. cmSystemTools::Message(e.str());
  2941. return false;
  2942. }
  2943. // Assume it is supported.
  2944. return true;
  2945. }
  2946. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  2947. const std::string& prop)
  2948. {
  2949. if (const char* val = target->GetProperty(prop)) {
  2950. mf->AddDefinition(prop, val);
  2951. }
  2952. }
  2953. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  2954. const std::string& targetName,
  2955. const std::string& fname)
  2956. {
  2957. // Find the Info.plist template.
  2958. const char* in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  2959. std::string inFile = (in && *in) ? in : "MacOSXBundleInfo.plist.in";
  2960. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2961. std::string inMod = this->Makefile->GetModulesFile(inFile);
  2962. if (!inMod.empty()) {
  2963. inFile = inMod;
  2964. }
  2965. }
  2966. if (!cmSystemTools::FileExists(inFile, true)) {
  2967. std::ostringstream e;
  2968. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2969. << "\" could not be found.";
  2970. cmSystemTools::Error(e.str());
  2971. return;
  2972. }
  2973. // Convert target properties to variables in an isolated makefile
  2974. // scope to configure the file. If properties are set they will
  2975. // override user make variables. If not the configuration will fall
  2976. // back to the directory-level values set by the user.
  2977. cmMakefile* mf = this->Makefile;
  2978. cmMakefile::ScopePushPop varScope(mf);
  2979. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
  2980. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  2981. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  2982. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  2983. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  2984. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  2985. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  2986. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  2987. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  2988. mf->ConfigureFile(inFile, fname, false, false, false);
  2989. }
  2990. void cmLocalGenerator::GenerateFrameworkInfoPList(
  2991. cmGeneratorTarget* target, const std::string& targetName,
  2992. const std::string& fname)
  2993. {
  2994. // Find the Info.plist template.
  2995. const char* in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  2996. std::string inFile = (in && *in) ? in : "MacOSXFrameworkInfo.plist.in";
  2997. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2998. std::string inMod = this->Makefile->GetModulesFile(inFile);
  2999. if (!inMod.empty()) {
  3000. inFile = inMod;
  3001. }
  3002. }
  3003. if (!cmSystemTools::FileExists(inFile, true)) {
  3004. std::ostringstream e;
  3005. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3006. << "\" could not be found.";
  3007. cmSystemTools::Error(e.str());
  3008. return;
  3009. }
  3010. // Convert target properties to variables in an isolated makefile
  3011. // scope to configure the file. If properties are set they will
  3012. // override user make variables. If not the configuration will fall
  3013. // back to the directory-level values set by the user.
  3014. cmMakefile* mf = this->Makefile;
  3015. cmMakefile::ScopePushPop varScope(mf);
  3016. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
  3017. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  3018. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  3019. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  3020. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  3021. mf->ConfigureFile(inFile, fname, false, false, false);
  3022. }