cmLocalGenerator.cxx 116 KB

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