cmLocalGenerator.cxx 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmLocalGenerator.h"
  4. #include "cmAlgorithms.h"
  5. #include "cmComputeLinkInformation.h"
  6. #include "cmCustomCommand.h"
  7. #include "cmCustomCommandGenerator.h"
  8. #include "cmCustomCommandLines.h"
  9. #include "cmGeneratedFileStream.h"
  10. #include "cmGeneratorExpression.h"
  11. #include "cmGeneratorExpressionEvaluationFile.h"
  12. #include "cmGeneratorTarget.h"
  13. #include "cmGlobalGenerator.h"
  14. #include "cmInstallGenerator.h"
  15. #include "cmInstallScriptGenerator.h"
  16. #include "cmInstallTargetGenerator.h"
  17. #include "cmLinkLineComputer.h"
  18. #include "cmLinkLineDeviceComputer.h"
  19. #include "cmMakefile.h"
  20. #include "cmRulePlaceholderExpander.h"
  21. #include "cmSourceFile.h"
  22. #include "cmSourceFileLocation.h"
  23. #include "cmSourceFileLocationKind.h"
  24. #include "cmState.h"
  25. #include "cmStateDirectory.h"
  26. #include "cmStateTypes.h"
  27. #include "cmStringAlgorithms.h"
  28. #include "cmSystemTools.h"
  29. #include "cmTarget.h"
  30. #include "cmTestGenerator.h"
  31. #include "cmVersion.h"
  32. #include "cmake.h"
  33. #include "cmsys/RegularExpression.hxx"
  34. #if !defined(CMAKE_BOOTSTRAP)
  35. # define CM_LG_ENCODE_OBJECT_NAMES
  36. # include "cmCryptoHash.h"
  37. #endif
  38. #include <cm/string_view>
  39. #include <algorithm>
  40. #include <cassert>
  41. #include <cstdio>
  42. #include <cstdlib>
  43. #include <cstring>
  44. #include <functional>
  45. #include <initializer_list>
  46. #include <iterator>
  47. #include <memory>
  48. #include <sstream>
  49. #include <unordered_set>
  50. #include <utility>
  51. #include <vector>
  52. #if defined(__HAIKU__)
  53. # include <FindDirectory.h>
  54. # include <StorageDefs.h>
  55. #endif
  56. // List of variables that are replaced when
  57. // rules are expanced. These variables are
  58. // replaced in the form <var> with GetSafeDefinition(var).
  59. // ${LANG} is replaced in the variable first with all enabled
  60. // languages.
  61. static auto ruleReplaceVars = { "CMAKE_${LANG}_COMPILER",
  62. "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
  63. "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
  64. "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
  65. "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
  66. "CMAKE_${LANG}_LINK_FLAGS",
  67. "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
  68. "CMAKE_${LANG}_ARCHIVE",
  69. "CMAKE_AR",
  70. "CMAKE_CURRENT_SOURCE_DIR",
  71. "CMAKE_CURRENT_BINARY_DIR",
  72. "CMAKE_RANLIB",
  73. "CMAKE_LINKER",
  74. "CMAKE_MT",
  75. "CMAKE_CUDA_HOST_COMPILER",
  76. "CMAKE_CUDA_HOST_LINK_LAUNCHER",
  77. "CMAKE_CL_SHOWINCLUDES_PREFIX" };
  78. cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
  79. : cmOutputConverter(makefile->GetStateSnapshot())
  80. , StateSnapshot(makefile->GetStateSnapshot())
  81. , DirectoryBacktrace(makefile->GetBacktrace())
  82. {
  83. this->GlobalGenerator = gg;
  84. this->Makefile = makefile;
  85. this->AliasTargets = makefile->GetAliasTargets();
  86. this->EmitUniversalBinaryFlags = true;
  87. this->BackwardsCompatibility = 0;
  88. this->BackwardsCompatibilityFinal = false;
  89. this->ComputeObjectMaxPath();
  90. // Canonicalize entries of the CPATH environment variable the same
  91. // way detection of CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES does.
  92. {
  93. std::vector<std::string> cpath;
  94. cmSystemTools::GetPath(cpath, "CPATH");
  95. for (std::string& cp : cpath) {
  96. if (cmSystemTools::FileIsFullPath(cp)) {
  97. cp = cmSystemTools::CollapseFullPath(cp);
  98. this->EnvCPATH.emplace(std::move(cp));
  99. }
  100. }
  101. }
  102. std::vector<std::string> enabledLanguages =
  103. this->GetState()->GetEnabledLanguages();
  104. if (const char* sysrootCompile =
  105. this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
  106. this->CompilerSysroot = sysrootCompile;
  107. } else {
  108. this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  109. }
  110. if (const char* sysrootLink =
  111. this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
  112. this->LinkerSysroot = sysrootLink;
  113. } else {
  114. this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  115. }
  116. for (std::string const& lang : enabledLanguages) {
  117. if (lang == "NONE") {
  118. continue;
  119. }
  120. this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
  121. this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
  122. this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
  123. std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
  124. std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
  125. std::string const& compilerOptionTarget =
  126. "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
  127. std::string const& compilerExternalToolchain =
  128. "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
  129. std::string const& compilerOptionExternalToolchain =
  130. "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
  131. std::string const& compilerOptionSysroot =
  132. "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
  133. this->VariableMappings[compilerArg1] =
  134. this->Makefile->GetSafeDefinition(compilerArg1);
  135. this->VariableMappings[compilerTarget] =
  136. this->Makefile->GetSafeDefinition(compilerTarget);
  137. this->VariableMappings[compilerOptionTarget] =
  138. this->Makefile->GetSafeDefinition(compilerOptionTarget);
  139. this->VariableMappings[compilerExternalToolchain] =
  140. this->Makefile->GetSafeDefinition(compilerExternalToolchain);
  141. this->VariableMappings[compilerOptionExternalToolchain] =
  142. this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
  143. this->VariableMappings[compilerOptionSysroot] =
  144. this->Makefile->GetSafeDefinition(compilerOptionSysroot);
  145. for (std::string replaceVar : ruleReplaceVars) {
  146. if (replaceVar.find("${LANG}") != std::string::npos) {
  147. cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
  148. }
  149. this->VariableMappings[replaceVar] =
  150. this->Makefile->GetSafeDefinition(replaceVar);
  151. }
  152. }
  153. }
  154. cmRulePlaceholderExpander* cmLocalGenerator::CreateRulePlaceholderExpander()
  155. const
  156. {
  157. return new cmRulePlaceholderExpander(this->Compilers, this->VariableMappings,
  158. this->CompilerSysroot,
  159. this->LinkerSysroot);
  160. }
  161. cmLocalGenerator::~cmLocalGenerator()
  162. {
  163. cmDeleteAll(this->GeneratorTargets);
  164. cmDeleteAll(this->OwnedImportedGeneratorTargets);
  165. }
  166. void cmLocalGenerator::IssueMessage(MessageType t,
  167. std::string const& text) const
  168. {
  169. this->GetCMakeInstance()->IssueMessage(t, text, this->DirectoryBacktrace);
  170. }
  171. void cmLocalGenerator::ComputeObjectMaxPath()
  172. {
  173. // Choose a maximum object file name length.
  174. #if defined(_WIN32) || defined(__CYGWIN__)
  175. this->ObjectPathMax = 250;
  176. #else
  177. this->ObjectPathMax = 1000;
  178. #endif
  179. const char* plen = this->Makefile->GetDefinition("CMAKE_OBJECT_PATH_MAX");
  180. if (plen && *plen) {
  181. unsigned int pmax;
  182. if (sscanf(plen, "%u", &pmax) == 1) {
  183. if (pmax >= 128) {
  184. this->ObjectPathMax = pmax;
  185. } else {
  186. std::ostringstream w;
  187. w << "CMAKE_OBJECT_PATH_MAX is set to " << pmax
  188. << ", which is less than the minimum of 128. "
  189. << "The value will be ignored.";
  190. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  191. }
  192. } else {
  193. std::ostringstream w;
  194. w << "CMAKE_OBJECT_PATH_MAX is set to \"" << plen
  195. << "\", which fails to parse as a positive integer. "
  196. << "The value will be ignored.";
  197. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  198. }
  199. }
  200. this->ObjectMaxPathViolations.clear();
  201. }
  202. static void MoveSystemIncludesToEnd(std::vector<std::string>& includeDirs,
  203. const std::string& config,
  204. const std::string& lang,
  205. const cmGeneratorTarget* target)
  206. {
  207. if (!target) {
  208. return;
  209. }
  210. std::stable_sort(
  211. includeDirs.begin(), includeDirs.end(),
  212. [&target, &config, &lang](std::string const& a, std::string const& b) {
  213. return !target->IsSystemIncludeDirectory(a, config, lang) &&
  214. target->IsSystemIncludeDirectory(b, config, lang);
  215. });
  216. }
  217. static void MoveSystemIncludesToEnd(std::vector<BT<std::string>>& includeDirs,
  218. const std::string& config,
  219. const std::string& lang,
  220. const cmGeneratorTarget* target)
  221. {
  222. if (!target) {
  223. return;
  224. }
  225. std::stable_sort(includeDirs.begin(), includeDirs.end(),
  226. [target, &config, &lang](BT<std::string> const& a,
  227. BT<std::string> const& b) {
  228. return !target->IsSystemIncludeDirectory(a.Value, config,
  229. lang) &&
  230. target->IsSystemIncludeDirectory(b.Value, config, lang);
  231. });
  232. }
  233. void cmLocalGenerator::TraceDependencies()
  234. {
  235. std::vector<std::string> const& configs =
  236. this->Makefile->GetGeneratorConfigs();
  237. for (std::string const& c : configs) {
  238. this->GlobalGenerator->CreateEvaluationSourceFiles(c);
  239. }
  240. // Generate the rule files for each target.
  241. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  242. for (cmGeneratorTarget* target : targets) {
  243. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  244. continue;
  245. }
  246. target->TraceDependencies();
  247. }
  248. }
  249. void cmLocalGenerator::GenerateTestFiles()
  250. {
  251. if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
  252. return;
  253. }
  254. // Compute the set of configurations.
  255. std::vector<std::string> configurationTypes;
  256. const std::string& config =
  257. this->Makefile->GetConfigurations(configurationTypes, false);
  258. std::string file =
  259. cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentBinary(),
  260. "/CTestTestfile.cmake");
  261. cmGeneratedFileStream fout(file);
  262. fout.SetCopyIfDifferent(true);
  263. fout << "# CMake generated Testfile for " << std::endl
  264. << "# Source directory: "
  265. << this->StateSnapshot.GetDirectory().GetCurrentSource() << std::endl
  266. << "# Build directory: "
  267. << this->StateSnapshot.GetDirectory().GetCurrentBinary() << std::endl
  268. << "# " << std::endl
  269. << "# This file includes the relevant testing commands "
  270. << "required for " << std::endl
  271. << "# testing this directory and lists subdirectories to "
  272. << "be tested as well." << std::endl;
  273. const char* testIncludeFile =
  274. this->Makefile->GetProperty("TEST_INCLUDE_FILE");
  275. if (testIncludeFile) {
  276. fout << "include(\"" << testIncludeFile << "\")" << std::endl;
  277. }
  278. const char* testIncludeFiles =
  279. this->Makefile->GetProperty("TEST_INCLUDE_FILES");
  280. if (testIncludeFiles) {
  281. std::vector<std::string> includesList = cmExpandedList(testIncludeFiles);
  282. for (std::string const& i : includesList) {
  283. fout << "include(\"" << i << "\")" << std::endl;
  284. }
  285. }
  286. // Ask each test generator to write its code.
  287. std::vector<cmTestGenerator*> const& testers =
  288. this->Makefile->GetTestGenerators();
  289. for (cmTestGenerator* tester : testers) {
  290. tester->Compute(this);
  291. tester->Generate(fout, config, configurationTypes);
  292. }
  293. using vec_t = std::vector<cmStateSnapshot>;
  294. vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
  295. std::string parentBinDir = this->GetCurrentBinaryDirectory();
  296. for (cmStateSnapshot const& i : children) {
  297. // TODO: Use add_subdirectory instead?
  298. std::string outP = i.GetDirectory().GetCurrentBinary();
  299. outP = this->MaybeConvertToRelativePath(parentBinDir, outP);
  300. outP = cmOutputConverter::EscapeForCMake(outP);
  301. fout << "subdirs(" << outP << ")" << std::endl;
  302. }
  303. // Add directory labels property
  304. const char* directoryLabels =
  305. this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
  306. const char* labels = this->Makefile->GetProperty("LABELS");
  307. if (labels || directoryLabels) {
  308. fout << "set_directory_properties(PROPERTIES LABELS ";
  309. if (labels) {
  310. fout << cmOutputConverter::EscapeForCMake(labels);
  311. }
  312. if (labels && directoryLabels) {
  313. fout << ";";
  314. }
  315. if (directoryLabels) {
  316. fout << cmOutputConverter::EscapeForCMake(directoryLabels);
  317. }
  318. fout << ")" << std::endl;
  319. }
  320. }
  321. void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
  322. {
  323. std::vector<cmGeneratorExpressionEvaluationFile*> ef =
  324. this->Makefile->GetEvaluationFiles();
  325. for (cmGeneratorExpressionEvaluationFile* geef : ef) {
  326. geef->CreateOutputFile(this, config);
  327. }
  328. }
  329. void cmLocalGenerator::ProcessEvaluationFiles(
  330. std::vector<std::string>& generatedFiles)
  331. {
  332. for (cmGeneratorExpressionEvaluationFile* geef :
  333. this->Makefile->GetEvaluationFiles()) {
  334. geef->Generate(this);
  335. if (cmSystemTools::GetFatalErrorOccured()) {
  336. return;
  337. }
  338. std::vector<std::string> files = geef->GetFiles();
  339. std::sort(files.begin(), files.end());
  340. std::vector<std::string> intersection;
  341. std::set_intersection(files.begin(), files.end(), generatedFiles.begin(),
  342. generatedFiles.end(),
  343. std::back_inserter(intersection));
  344. if (!intersection.empty()) {
  345. cmSystemTools::Error("Files to be generated by multiple different "
  346. "commands: " +
  347. cmWrap('"', intersection, '"', " "));
  348. return;
  349. }
  350. cmAppend(generatedFiles, files);
  351. std::inplace_merge(generatedFiles.begin(),
  352. generatedFiles.end() - files.size(),
  353. generatedFiles.end());
  354. }
  355. }
  356. void cmLocalGenerator::GenerateInstallRules()
  357. {
  358. // Compute the install prefix.
  359. const char* prefix = this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
  360. #if defined(_WIN32) && !defined(__CYGWIN__)
  361. std::string prefix_win32;
  362. if (!prefix) {
  363. if (!cmSystemTools::GetEnv("SystemDrive", prefix_win32)) {
  364. prefix_win32 = "C:";
  365. }
  366. const char* project_name = this->Makefile->GetDefinition("PROJECT_NAME");
  367. if (project_name && project_name[0]) {
  368. prefix_win32 += "/Program Files/";
  369. prefix_win32 += project_name;
  370. } else {
  371. prefix_win32 += "/InstalledCMakeProject";
  372. }
  373. prefix = prefix_win32.c_str();
  374. }
  375. #elif defined(__HAIKU__)
  376. char dir[B_PATH_NAME_LENGTH];
  377. if (!prefix) {
  378. if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  379. B_OK) {
  380. prefix = dir;
  381. } else {
  382. prefix = "/boot/system";
  383. }
  384. }
  385. #else
  386. if (!prefix) {
  387. prefix = "/usr/local";
  388. }
  389. #endif
  390. if (const char* stagingPrefix =
  391. this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
  392. prefix = stagingPrefix;
  393. }
  394. // Compute the set of configurations.
  395. std::vector<std::string> configurationTypes;
  396. const std::string& config =
  397. this->Makefile->GetConfigurations(configurationTypes, false);
  398. // Choose a default install configuration.
  399. std::string default_config = config;
  400. const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
  401. "DEBUG", nullptr };
  402. for (const char** c = default_order; *c && default_config.empty(); ++c) {
  403. for (std::string const& configurationType : configurationTypes) {
  404. if (cmSystemTools::UpperCase(configurationType) == *c) {
  405. default_config = configurationType;
  406. }
  407. }
  408. }
  409. if (default_config.empty() && !configurationTypes.empty()) {
  410. default_config = configurationTypes[0];
  411. }
  412. // Create the install script file.
  413. std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  414. std::string homedir = this->GetState()->GetBinaryDirectory();
  415. int toplevel_install = 0;
  416. if (file == homedir) {
  417. toplevel_install = 1;
  418. }
  419. file += "/cmake_install.cmake";
  420. cmGeneratedFileStream fout(file);
  421. fout.SetCopyIfDifferent(true);
  422. // Write the header.
  423. fout << "# Install script for directory: "
  424. << this->StateSnapshot.GetDirectory().GetCurrentSource() << std::endl
  425. << std::endl;
  426. fout << "# Set the install prefix" << std::endl
  427. << "if(NOT DEFINED CMAKE_INSTALL_PREFIX)" << std::endl
  428. << " set(CMAKE_INSTALL_PREFIX \"" << prefix << "\")" << std::endl
  429. << "endif()" << std::endl
  430. << R"(string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX )"
  431. << "\"${CMAKE_INSTALL_PREFIX}\")" << std::endl
  432. << std::endl;
  433. // Write support code for generating per-configuration install rules.
  434. /* clang-format off */
  435. fout <<
  436. "# Set the install configuration name.\n"
  437. "if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
  438. " if(BUILD_TYPE)\n"
  439. " string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
  440. " CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
  441. " else()\n"
  442. " set(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
  443. " endif()\n"
  444. " message(STATUS \"Install configuration: "
  445. "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
  446. "endif()\n"
  447. "\n";
  448. /* clang-format on */
  449. // Write support code for dealing with component-specific installs.
  450. /* clang-format off */
  451. fout <<
  452. "# Set the component getting installed.\n"
  453. "if(NOT CMAKE_INSTALL_COMPONENT)\n"
  454. " if(COMPONENT)\n"
  455. " message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
  456. " set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
  457. " else()\n"
  458. " set(CMAKE_INSTALL_COMPONENT)\n"
  459. " endif()\n"
  460. "endif()\n"
  461. "\n";
  462. /* clang-format on */
  463. // Copy user-specified install options to the install code.
  464. if (const char* so_no_exe =
  465. this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE")) {
  466. /* clang-format off */
  467. fout <<
  468. "# Install shared libraries without execute permission?\n"
  469. "if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
  470. " set(CMAKE_INSTALL_SO_NO_EXE \"" << so_no_exe << "\")\n"
  471. "endif()\n"
  472. "\n";
  473. /* clang-format on */
  474. }
  475. // Copy cmake cross compile state to install code.
  476. if (const char* crosscompiling =
  477. this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
  478. /* clang-format off */
  479. fout <<
  480. "# Is this installation the result of a crosscompile?\n"
  481. "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
  482. " set(CMAKE_CROSSCOMPILING \"" << crosscompiling << "\")\n"
  483. "endif()\n"
  484. "\n";
  485. /* clang-format on */
  486. }
  487. // Write default directory permissions.
  488. if (const char* defaultDirPermissions = this->Makefile->GetDefinition(
  489. "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS")) {
  490. /* clang-format off */
  491. fout <<
  492. "# Set default install directory permissions.\n"
  493. "if(NOT DEFINED CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS)\n"
  494. " set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS \""
  495. << defaultDirPermissions << "\")\n"
  496. "endif()\n"
  497. "\n";
  498. /* clang-format on */
  499. }
  500. // Ask each install generator to write its code.
  501. cmPolicies::PolicyStatus status = this->GetPolicyStatus(cmPolicies::CMP0082);
  502. std::vector<cmInstallGenerator*> const& installers =
  503. this->Makefile->GetInstallGenerators();
  504. bool haveSubdirectoryInstall = false;
  505. bool haveInstallAfterSubdirectory = false;
  506. if (status == cmPolicies::WARN) {
  507. for (cmInstallGenerator* installer : installers) {
  508. installer->CheckCMP0082(haveSubdirectoryInstall,
  509. haveInstallAfterSubdirectory);
  510. installer->Generate(fout, config, configurationTypes);
  511. }
  512. } else {
  513. for (cmInstallGenerator* installer : installers) {
  514. installer->Generate(fout, config, configurationTypes);
  515. }
  516. }
  517. // Write rules from old-style specification stored in targets.
  518. this->GenerateTargetInstallRules(fout, config, configurationTypes);
  519. // Include install scripts from subdirectories.
  520. switch (status) {
  521. case cmPolicies::WARN:
  522. if (haveInstallAfterSubdirectory &&
  523. this->Makefile->PolicyOptionalWarningEnabled(
  524. "CMAKE_POLICY_WARNING_CMP0082")) {
  525. std::ostringstream e;
  526. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0082) << "\n";
  527. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  528. }
  529. CM_FALLTHROUGH;
  530. case cmPolicies::OLD: {
  531. std::vector<cmStateSnapshot> children =
  532. this->Makefile->GetStateSnapshot().GetChildren();
  533. if (!children.empty()) {
  534. fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
  535. fout << " # Include the install script for each subdirectory.\n";
  536. for (cmStateSnapshot const& c : children) {
  537. if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  538. std::string odir = c.GetDirectory().GetCurrentBinary();
  539. cmSystemTools::ConvertToUnixSlashes(odir);
  540. fout << " include(\"" << odir << "/cmake_install.cmake\")"
  541. << std::endl;
  542. }
  543. }
  544. fout << "\n";
  545. fout << "endif()\n\n";
  546. }
  547. } break;
  548. case cmPolicies::REQUIRED_IF_USED:
  549. case cmPolicies::REQUIRED_ALWAYS:
  550. case cmPolicies::NEW:
  551. // NEW behavior is handled in
  552. // cmInstallSubdirectoryGenerator::GenerateScript()
  553. break;
  554. }
  555. // Record the install manifest.
  556. if (toplevel_install) {
  557. /* clang-format off */
  558. fout <<
  559. "if(CMAKE_INSTALL_COMPONENT)\n"
  560. " set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
  561. "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
  562. "else()\n"
  563. " set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
  564. "endif()\n"
  565. "\n"
  566. "string(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n"
  567. " \"${CMAKE_INSTALL_MANIFEST_FILES}\")\n"
  568. "file(WRITE \"" << homedir << "/${CMAKE_INSTALL_MANIFEST}\"\n"
  569. " \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n";
  570. /* clang-format on */
  571. }
  572. }
  573. void cmLocalGenerator::AddGeneratorTarget(cmGeneratorTarget* gt)
  574. {
  575. this->GeneratorTargets.push_back(gt);
  576. this->GeneratorTargetSearchIndex.emplace(gt->GetName(), gt);
  577. this->GlobalGenerator->IndexGeneratorTarget(gt);
  578. }
  579. void cmLocalGenerator::AddImportedGeneratorTarget(cmGeneratorTarget* gt)
  580. {
  581. this->ImportedGeneratorTargets.emplace(gt->GetName(), gt);
  582. this->GlobalGenerator->IndexGeneratorTarget(gt);
  583. }
  584. void cmLocalGenerator::AddOwnedImportedGeneratorTarget(cmGeneratorTarget* gt)
  585. {
  586. this->OwnedImportedGeneratorTargets.push_back(gt);
  587. }
  588. cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
  589. const std::string& name) const
  590. {
  591. auto ti = this->GeneratorTargetSearchIndex.find(name);
  592. if (ti != this->GeneratorTargetSearchIndex.end()) {
  593. return ti->second;
  594. }
  595. return nullptr;
  596. }
  597. void cmLocalGenerator::ComputeTargetManifest()
  598. {
  599. // Collect the set of configuration types.
  600. std::vector<std::string> configNames;
  601. this->Makefile->GetConfigurations(configNames);
  602. if (configNames.empty()) {
  603. configNames.emplace_back();
  604. }
  605. // Add our targets to the manifest for each configuration.
  606. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  607. for (cmGeneratorTarget* target : targets) {
  608. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  609. continue;
  610. }
  611. for (std::string const& c : configNames) {
  612. target->ComputeTargetManifest(c);
  613. }
  614. }
  615. }
  616. bool cmLocalGenerator::ComputeTargetCompileFeatures()
  617. {
  618. // Collect the set of configuration types.
  619. std::vector<std::string> configNames;
  620. this->Makefile->GetConfigurations(configNames);
  621. if (configNames.empty()) {
  622. configNames.emplace_back();
  623. }
  624. // Process compile features of all targets.
  625. const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
  626. for (cmGeneratorTarget* target : targets) {
  627. for (std::string const& c : configNames) {
  628. if (!target->ComputeCompileFeatures(c)) {
  629. return false;
  630. }
  631. }
  632. }
  633. return true;
  634. }
  635. bool cmLocalGenerator::IsRootMakefile() const
  636. {
  637. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  638. }
  639. cmState* cmLocalGenerator::GetState() const
  640. {
  641. return this->GlobalGenerator->GetCMakeInstance()->GetState();
  642. }
  643. cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
  644. {
  645. return this->Makefile->GetStateSnapshot();
  646. }
  647. const char* cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
  648. const std::string& prop)
  649. {
  650. if (target) {
  651. return target->GetProperty(prop);
  652. }
  653. return this->Makefile->GetProperty(prop);
  654. }
  655. std::string cmLocalGenerator::ConvertToIncludeReference(
  656. std::string const& path, OutputFormat format, bool forceFullPaths)
  657. {
  658. static_cast<void>(forceFullPaths);
  659. return this->ConvertToOutputForExisting(path, format);
  660. }
  661. std::string cmLocalGenerator::GetIncludeFlags(
  662. const std::vector<std::string>& includeDirs, cmGeneratorTarget* target,
  663. const std::string& lang, bool forceFullPaths, bool forResponseFile,
  664. const std::string& config)
  665. {
  666. if (lang.empty()) {
  667. return "";
  668. }
  669. std::vector<std::string> includes = includeDirs;
  670. MoveSystemIncludesToEnd(includes, config, lang, target);
  671. OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
  672. std::ostringstream includeFlags;
  673. std::string const& includeFlag =
  674. this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
  675. const char* sep =
  676. this->Makefile->GetDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_SEP_", lang));
  677. bool quotePaths = false;
  678. if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
  679. quotePaths = true;
  680. }
  681. bool repeatFlag = true;
  682. // should the include flag be repeated like ie. -IA -IB
  683. if (!sep) {
  684. sep = " ";
  685. } else {
  686. // if there is a separator then the flag is not repeated but is only
  687. // given once i.e. -classpath a:b:c
  688. repeatFlag = false;
  689. }
  690. // Support special system include flag if it is available and the
  691. // normal flag is repeated for each directory.
  692. const char* sysIncludeFlag = nullptr;
  693. if (repeatFlag) {
  694. sysIncludeFlag = this->Makefile->GetDefinition(
  695. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
  696. }
  697. const char* fwSearchFlag = this->Makefile->GetDefinition(
  698. cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
  699. const char* sysFwSearchFlag = this->Makefile->GetDefinition(
  700. cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
  701. bool flagUsed = false;
  702. std::set<std::string> emitted;
  703. #ifdef __APPLE__
  704. emitted.insert("/System/Library/Frameworks");
  705. #endif
  706. for (std::string const& i : includes) {
  707. if (fwSearchFlag && *fwSearchFlag && this->Makefile->IsOn("APPLE") &&
  708. cmSystemTools::IsPathToFramework(i)) {
  709. std::string const frameworkDir =
  710. cmSystemTools::CollapseFullPath(cmStrCat(i, "/../"));
  711. if (emitted.insert(frameworkDir).second) {
  712. if (sysFwSearchFlag && target &&
  713. target->IsSystemIncludeDirectory(i, config, lang)) {
  714. includeFlags << sysFwSearchFlag;
  715. } else {
  716. includeFlags << fwSearchFlag;
  717. }
  718. includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
  719. << " ";
  720. }
  721. continue;
  722. }
  723. if (!flagUsed || repeatFlag) {
  724. if (sysIncludeFlag && target &&
  725. target->IsSystemIncludeDirectory(i, config, lang)) {
  726. includeFlags << sysIncludeFlag;
  727. } else {
  728. includeFlags << includeFlag;
  729. }
  730. flagUsed = true;
  731. }
  732. std::string includePath =
  733. this->ConvertToIncludeReference(i, shellFormat, forceFullPaths);
  734. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  735. includeFlags << "\"";
  736. }
  737. includeFlags << includePath;
  738. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  739. includeFlags << "\"";
  740. }
  741. includeFlags << sep;
  742. }
  743. std::string flags = includeFlags.str();
  744. // remove trailing separators
  745. if ((sep[0] != ' ') && !flags.empty() && flags.back() == sep[0]) {
  746. flags.back() = ' ';
  747. }
  748. return flags;
  749. }
  750. void cmLocalGenerator::AddCompileOptions(std::string& flags,
  751. cmGeneratorTarget* target,
  752. const std::string& lang,
  753. const std::string& config)
  754. {
  755. std::vector<BT<std::string>> tmpFlags;
  756. this->AddCompileOptions(tmpFlags, target, lang, config);
  757. this->AppendFlags(flags, tmpFlags);
  758. }
  759. void cmLocalGenerator::AddCompileOptions(std::vector<BT<std::string>>& flags,
  760. cmGeneratorTarget* target,
  761. const std::string& lang,
  762. const std::string& config)
  763. {
  764. std::string langFlagRegexVar = std::string("CMAKE_") + lang + "_FLAG_REGEX";
  765. if (const char* langFlagRegexStr =
  766. this->Makefile->GetDefinition(langFlagRegexVar)) {
  767. // Filter flags acceptable to this language.
  768. if (const char* targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  769. std::vector<std::string> opts;
  770. cmSystemTools::ParseWindowsCommandLine(targetFlags, opts);
  771. // Re-escape these flags since COMPILE_FLAGS were already parsed
  772. // as a command line above.
  773. std::string compileOpts;
  774. this->AppendCompileOptions(compileOpts, opts, langFlagRegexStr);
  775. if (!compileOpts.empty()) {
  776. flags.emplace_back(std::move(compileOpts));
  777. }
  778. }
  779. std::vector<BT<std::string>> targetCompileOpts =
  780. target->GetCompileOptions(config, lang);
  781. // COMPILE_OPTIONS are escaped.
  782. this->AppendCompileOptions(flags, targetCompileOpts, langFlagRegexStr);
  783. } else {
  784. // Use all flags.
  785. if (const char* targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  786. // COMPILE_FLAGS are not escaped for historical reasons.
  787. std::string compileFlags;
  788. this->AppendFlags(compileFlags, targetFlags);
  789. if (!compileFlags.empty()) {
  790. flags.emplace_back(std::move(compileFlags));
  791. }
  792. }
  793. std::vector<BT<std::string>> targetCompileOpts =
  794. target->GetCompileOptions(config, lang);
  795. // COMPILE_OPTIONS are escaped.
  796. this->AppendCompileOptions(flags, targetCompileOpts);
  797. }
  798. for (auto const& it : target->GetMaxLanguageStandards()) {
  799. const char* standard = target->GetProperty(it.first + "_STANDARD");
  800. if (!standard) {
  801. continue;
  802. }
  803. if (this->Makefile->IsLaterStandard(it.first, standard, it.second)) {
  804. std::ostringstream e;
  805. e << "The COMPILE_FEATURES property of target \"" << target->GetName()
  806. << "\" was evaluated when computing the link "
  807. "implementation, and the \""
  808. << it.first << "_STANDARD\" was \"" << it.second
  809. << "\" for that computation. Computing the "
  810. "COMPILE_FEATURES based on the link implementation resulted in a "
  811. "higher \""
  812. << it.first << "_STANDARD\" \"" << standard
  813. << "\". "
  814. "This is not permitted. The COMPILE_FEATURES may not both depend "
  815. "on "
  816. "and be depended on by the link implementation."
  817. << std::endl;
  818. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  819. return;
  820. }
  821. }
  822. std::string compReqFlag;
  823. this->AddCompilerRequirementFlag(compReqFlag, target, lang);
  824. if (!compReqFlag.empty()) {
  825. flags.emplace_back(std::move(compReqFlag));
  826. }
  827. // Add compile flag for the MSVC compiler only.
  828. cmMakefile* mf = this->GetMakefile();
  829. if (const char* jmc =
  830. mf->GetDefinition("CMAKE_" + lang + "_COMPILE_OPTIONS_JMC")) {
  831. // Handle Just My Code debugging flags, /JMC.
  832. // If the target is a Managed C++ one, /JMC is not compatible.
  833. if (target->GetManagedType(config) !=
  834. cmGeneratorTarget::ManagedType::Managed) {
  835. // add /JMC flags if target property VS_JUST_MY_CODE_DEBUGGING is set
  836. // to ON
  837. if (char const* jmcExprGen =
  838. target->GetProperty("VS_JUST_MY_CODE_DEBUGGING")) {
  839. cmGeneratorExpression ge;
  840. std::unique_ptr<cmCompiledGeneratorExpression> cge =
  841. ge.Parse(jmcExprGen);
  842. std::string isJMCEnabled = cge->Evaluate(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')) {
  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. cmGeneratorExpression ge;
  1542. std::unique_ptr<cmCompiledGeneratorExpression> cge =
  1543. ge.Parse(msvcRuntimeLibraryValue);
  1544. std::string const msvcRuntimeLibrary = cge->Evaluate(this, config, target);
  1545. if (!msvcRuntimeLibrary.empty()) {
  1546. if (const char* msvcRuntimeLibraryOptions =
  1547. this->Makefile->GetDefinition(
  1548. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1549. msvcRuntimeLibrary)) {
  1550. this->AppendCompileOptions(flags, msvcRuntimeLibraryOptions);
  1551. } else if ((this->Makefile->GetSafeDefinition(
  1552. "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
  1553. this->Makefile->GetSafeDefinition(
  1554. "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
  1555. !cmSystemTools::GetErrorOccuredFlag()) {
  1556. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1557. this->IssueMessage(MessageType::FATAL_ERROR,
  1558. "MSVC_RUNTIME_LIBRARY value '" +
  1559. msvcRuntimeLibrary + "' not known for this " +
  1560. lang + " compiler.");
  1561. }
  1562. }
  1563. }
  1564. }
  1565. void cmLocalGenerator::AddLanguageFlagsForLinking(
  1566. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  1567. const std::string& config)
  1568. {
  1569. if (this->Makefile->IsOn("CMAKE_" + lang +
  1570. "_LINK_WITH_STANDARD_COMPILE_OPTION")) {
  1571. // This toolchain requires use of the language standard flag
  1572. // when linking in order to use the matching standard library.
  1573. // FIXME: If CMake gains an abstraction for standard library
  1574. // selection, this will have to be reconciled with it.
  1575. this->AddCompilerRequirementFlag(flags, target, lang);
  1576. }
  1577. this->AddLanguageFlags(flags, target, lang, config);
  1578. if (target->IsIPOEnabled(lang, config)) {
  1579. this->AppendFeatureOptions(flags, lang, "IPO");
  1580. }
  1581. }
  1582. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  1583. const std::string& name) const
  1584. {
  1585. auto imported = this->ImportedGeneratorTargets.find(name);
  1586. if (imported != this->ImportedGeneratorTargets.end()) {
  1587. return imported->second;
  1588. }
  1589. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  1590. return t;
  1591. }
  1592. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  1593. }
  1594. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  1595. const std::string& config,
  1596. std::string& dep)
  1597. {
  1598. // Older CMake code may specify the dependency using the target
  1599. // output file rather than the target name. Such code would have
  1600. // been written before there was support for target properties that
  1601. // modify the name so stripping down to just the file name should
  1602. // produce the target name in this case.
  1603. std::string name = cmSystemTools::GetFilenameName(inName);
  1604. // If the input name is the empty string, there is no real
  1605. // dependency. Short-circuit the other checks:
  1606. if (name.empty()) {
  1607. return false;
  1608. }
  1609. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  1610. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  1611. }
  1612. // Look for a CMake target with the given name.
  1613. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  1614. // make sure it is not just a coincidence that the target name
  1615. // found is part of the inName
  1616. if (cmSystemTools::FileIsFullPath(inName)) {
  1617. std::string tLocation;
  1618. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  1619. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  1620. tLocation = target->GetLocation(config);
  1621. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  1622. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  1623. }
  1624. std::string depLocation =
  1625. cmSystemTools::GetFilenamePath(std::string(inName));
  1626. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  1627. if (depLocation != tLocation) {
  1628. // it is a full path to a depend that has the same name
  1629. // as a target but is in a different location so do not use
  1630. // the target as the depend
  1631. dep = inName;
  1632. return true;
  1633. }
  1634. }
  1635. switch (target->GetType()) {
  1636. case cmStateEnums::EXECUTABLE:
  1637. case cmStateEnums::STATIC_LIBRARY:
  1638. case cmStateEnums::SHARED_LIBRARY:
  1639. case cmStateEnums::MODULE_LIBRARY:
  1640. case cmStateEnums::UNKNOWN_LIBRARY:
  1641. dep = target->GetLocation(config);
  1642. return true;
  1643. case cmStateEnums::OBJECT_LIBRARY:
  1644. // An object library has no single file on which to depend.
  1645. // This was listed to get the target-level dependency.
  1646. return false;
  1647. case cmStateEnums::INTERFACE_LIBRARY:
  1648. // An interface library has no file on which to depend.
  1649. // This was listed to get the target-level dependency.
  1650. return false;
  1651. case cmStateEnums::UTILITY:
  1652. case cmStateEnums::GLOBAL_TARGET:
  1653. // A utility target has no file on which to depend. This was listed
  1654. // only to get the target-level dependency.
  1655. return false;
  1656. }
  1657. }
  1658. // The name was not that of a CMake target. It must name a file.
  1659. if (cmSystemTools::FileIsFullPath(inName)) {
  1660. // This is a full path. Return it as given.
  1661. dep = inName;
  1662. return true;
  1663. }
  1664. // Check for a source file in this directory that matches the
  1665. // dependency.
  1666. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  1667. dep = sf->ResolveFullPath();
  1668. return true;
  1669. }
  1670. // Treat the name as relative to the source directory in which it
  1671. // was given.
  1672. dep = cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentSource(), '/',
  1673. inName);
  1674. return true;
  1675. }
  1676. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  1677. const std::string& lang, bool shared)
  1678. {
  1679. std::string flagsVar;
  1680. // Add flags for dealing with shared libraries for this language.
  1681. if (shared) {
  1682. this->AppendFlags(flags,
  1683. this->Makefile->GetSafeDefinition(
  1684. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS")));
  1685. }
  1686. }
  1687. void cmLocalGenerator::AddCompilerRequirementFlag(
  1688. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1689. {
  1690. if (lang.empty()) {
  1691. return;
  1692. }
  1693. const char* defaultStd =
  1694. this->Makefile->GetDefinition("CMAKE_" + lang + "_STANDARD_DEFAULT");
  1695. if (!defaultStd || !*defaultStd) {
  1696. // This compiler has no notion of language standard levels.
  1697. return;
  1698. }
  1699. std::string extProp = lang + "_EXTENSIONS";
  1700. bool ext = true;
  1701. if (const char* extPropValue = target->GetProperty(extProp)) {
  1702. if (cmIsOff(extPropValue)) {
  1703. ext = false;
  1704. }
  1705. }
  1706. std::string stdProp = lang + "_STANDARD";
  1707. const char* standardProp = target->GetProperty(stdProp);
  1708. if (!standardProp) {
  1709. if (ext) {
  1710. // No language standard is specified and extensions are not disabled.
  1711. // Check if this compiler needs a flag to enable extensions.
  1712. std::string const option_flag =
  1713. "CMAKE_" + lang + "_EXTENSION_COMPILE_OPTION";
  1714. if (const char* opt =
  1715. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1716. std::vector<std::string> optVec = cmExpandedList(opt);
  1717. for (std::string const& i : optVec) {
  1718. this->AppendFlagEscape(flags, i);
  1719. }
  1720. }
  1721. }
  1722. return;
  1723. }
  1724. std::string const type = ext ? "EXTENSION" : "STANDARD";
  1725. if (target->GetPropertyAsBool(lang + "_STANDARD_REQUIRED")) {
  1726. std::string option_flag =
  1727. "CMAKE_" + lang + standardProp + "_" + type + "_COMPILE_OPTION";
  1728. const char* opt =
  1729. target->Target->GetMakefile()->GetDefinition(option_flag);
  1730. if (!opt) {
  1731. std::ostringstream e;
  1732. e << "Target \"" << target->GetName()
  1733. << "\" requires the language "
  1734. "dialect \""
  1735. << lang << standardProp << "\" "
  1736. << (ext ? "(with compiler extensions)" : "")
  1737. << ", but CMake "
  1738. "does not know the compile flags to use to enable it.";
  1739. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1740. } else {
  1741. std::vector<std::string> optVec = cmExpandedList(opt);
  1742. for (std::string const& i : optVec) {
  1743. this->AppendFlagEscape(flags, i);
  1744. }
  1745. }
  1746. return;
  1747. }
  1748. static std::map<std::string, std::vector<std::string>> langStdMap;
  1749. if (langStdMap.empty()) {
  1750. // Maintain sorted order, most recent first.
  1751. langStdMap["CXX"].emplace_back("20");
  1752. langStdMap["CXX"].emplace_back("17");
  1753. langStdMap["CXX"].emplace_back("14");
  1754. langStdMap["CXX"].emplace_back("11");
  1755. langStdMap["CXX"].emplace_back("98");
  1756. langStdMap["C"].emplace_back("11");
  1757. langStdMap["C"].emplace_back("99");
  1758. langStdMap["C"].emplace_back("90");
  1759. langStdMap["CUDA"].emplace_back("14");
  1760. langStdMap["CUDA"].emplace_back("11");
  1761. langStdMap["CUDA"].emplace_back("98");
  1762. }
  1763. std::string standard(standardProp);
  1764. std::vector<std::string>& stds = langStdMap[lang];
  1765. auto stdIt = std::find(stds.begin(), stds.end(), standard);
  1766. if (stdIt == stds.end()) {
  1767. std::string e =
  1768. lang + "_STANDARD is set to invalid value '" + standard + "'";
  1769. this->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  1770. MessageType::FATAL_ERROR, e, target->GetBacktrace());
  1771. return;
  1772. }
  1773. auto defaultStdIt = std::find(stds.begin(), stds.end(), defaultStd);
  1774. if (defaultStdIt == stds.end()) {
  1775. std::string e = "CMAKE_" + lang +
  1776. "_STANDARD_DEFAULT is set to invalid value '" + std::string(defaultStd) +
  1777. "'";
  1778. this->IssueMessage(MessageType::INTERNAL_ERROR, e);
  1779. return;
  1780. }
  1781. // If the standard requested is older than the compiler's default
  1782. // then we need to use a flag to change it. The comparison is
  1783. // greater-or-equal because the standards are stored in backward
  1784. // chronological order.
  1785. if (stdIt >= defaultStdIt) {
  1786. std::string option_flag =
  1787. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  1788. std::string const& opt =
  1789. target->Target->GetMakefile()->GetRequiredDefinition(option_flag);
  1790. std::vector<std::string> optVec = cmExpandedList(opt);
  1791. for (std::string const& i : optVec) {
  1792. this->AppendFlagEscape(flags, i);
  1793. }
  1794. return;
  1795. }
  1796. // The standard requested is at least as new as the compiler's default,
  1797. // and the standard request is not required. Decay to the newest standard
  1798. // for which a flag is defined.
  1799. for (; stdIt < defaultStdIt; ++stdIt) {
  1800. std::string option_flag =
  1801. cmStrCat("CMAKE_", lang, *stdIt, "_", type, "_COMPILE_OPTION");
  1802. if (const char* opt =
  1803. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1804. std::vector<std::string> optVec = cmExpandedList(opt);
  1805. for (std::string const& i : optVec) {
  1806. this->AppendFlagEscape(flags, i);
  1807. }
  1808. return;
  1809. }
  1810. }
  1811. }
  1812. static void AddVisibilityCompileOption(std::string& flags,
  1813. cmGeneratorTarget const* target,
  1814. cmLocalGenerator* lg,
  1815. const std::string& lang,
  1816. std::string* warnCMP0063)
  1817. {
  1818. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  1819. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1820. if (!opt) {
  1821. return;
  1822. }
  1823. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  1824. const char* prop = target->GetProperty(flagDefine);
  1825. if (!prop) {
  1826. return;
  1827. }
  1828. if (warnCMP0063) {
  1829. *warnCMP0063 += " " + flagDefine + "\n";
  1830. return;
  1831. }
  1832. if (strcmp(prop, "hidden") != 0 && strcmp(prop, "default") != 0 &&
  1833. strcmp(prop, "protected") != 0 && strcmp(prop, "internal") != 0) {
  1834. std::ostringstream e;
  1835. e << "Target " << target->GetName() << " uses unsupported value \"" << prop
  1836. << "\" for " << flagDefine << "."
  1837. << " The supported values are: default, hidden, protected, and "
  1838. "internal.";
  1839. cmSystemTools::Error(e.str());
  1840. return;
  1841. }
  1842. std::string option = std::string(opt) + prop;
  1843. lg->AppendFlags(flags, option);
  1844. }
  1845. static void AddInlineVisibilityCompileOption(std::string& flags,
  1846. cmGeneratorTarget const* target,
  1847. cmLocalGenerator* lg,
  1848. std::string* warnCMP0063)
  1849. {
  1850. std::string compileOption =
  1851. "CMAKE_CXX_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN";
  1852. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1853. if (!opt) {
  1854. return;
  1855. }
  1856. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  1857. if (!prop) {
  1858. return;
  1859. }
  1860. if (warnCMP0063) {
  1861. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  1862. return;
  1863. }
  1864. lg->AppendFlags(flags, opt);
  1865. }
  1866. void cmLocalGenerator::AddVisibilityPresetFlags(
  1867. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1868. {
  1869. if (lang.empty()) {
  1870. return;
  1871. }
  1872. std::string warnCMP0063;
  1873. std::string* pWarnCMP0063 = nullptr;
  1874. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1875. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  1876. !target->IsExecutableWithExports()) {
  1877. switch (target->GetPolicyStatusCMP0063()) {
  1878. case cmPolicies::OLD:
  1879. return;
  1880. case cmPolicies::WARN:
  1881. pWarnCMP0063 = &warnCMP0063;
  1882. break;
  1883. default:
  1884. break;
  1885. }
  1886. }
  1887. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  1888. if (lang == "CXX") {
  1889. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063);
  1890. }
  1891. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  1892. std::ostringstream w;
  1893. /* clang-format off */
  1894. w <<
  1895. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  1896. "Target \"" << target->GetName() << "\" of "
  1897. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  1898. "has the following visibility properties set for " << lang << ":\n" <<
  1899. warnCMP0063 <<
  1900. "For compatibility CMake is not honoring them for this target.";
  1901. /* clang-format on */
  1902. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  1903. MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  1904. }
  1905. }
  1906. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  1907. cmGeneratorTarget const* target,
  1908. std::string const& lang,
  1909. const std::string& config)
  1910. {
  1911. int targetType = target->GetType();
  1912. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  1913. (targetType == cmStateEnums::MODULE_LIBRARY));
  1914. if (this->GetShouldUseOldFlags(shared, lang)) {
  1915. this->AddSharedFlags(flags, lang, shared);
  1916. } else {
  1917. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  1918. if (target->GetPropertyAsBool("POSITION_INDEPENDENT_CODE")) {
  1919. this->AddPositionIndependentFlags(flags, lang, targetType);
  1920. }
  1921. return;
  1922. }
  1923. if (target->GetLinkInterfaceDependentBoolProperty(
  1924. "POSITION_INDEPENDENT_CODE", config)) {
  1925. this->AddPositionIndependentFlags(flags, lang, targetType);
  1926. }
  1927. if (shared) {
  1928. this->AppendFeatureOptions(flags, lang, "DLL");
  1929. }
  1930. }
  1931. }
  1932. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  1933. const std::string& lang) const
  1934. {
  1935. std::string originalFlags =
  1936. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  1937. if (shared) {
  1938. std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  1939. std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
  1940. if (flags != originalFlags) {
  1941. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  1942. case cmPolicies::WARN: {
  1943. std::ostringstream e;
  1944. e << "Variable " << flagsVar
  1945. << " has been modified. CMake "
  1946. "will ignore the POSITION_INDEPENDENT_CODE target property for "
  1947. "shared libraries and will use the "
  1948. << flagsVar
  1949. << " variable "
  1950. "instead. This may cause errors if the original content of "
  1951. << flagsVar << " was removed.\n"
  1952. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  1953. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  1954. CM_FALLTHROUGH;
  1955. }
  1956. case cmPolicies::OLD:
  1957. return true;
  1958. case cmPolicies::REQUIRED_IF_USED:
  1959. case cmPolicies::REQUIRED_ALWAYS:
  1960. case cmPolicies::NEW:
  1961. return false;
  1962. }
  1963. }
  1964. }
  1965. return false;
  1966. }
  1967. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  1968. std::string const& lang,
  1969. int targetType)
  1970. {
  1971. std::string picFlags;
  1972. if (targetType == cmStateEnums::EXECUTABLE) {
  1973. picFlags = this->Makefile->GetSafeDefinition(
  1974. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
  1975. }
  1976. if (picFlags.empty()) {
  1977. picFlags = this->Makefile->GetSafeDefinition(
  1978. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
  1979. }
  1980. if (!picFlags.empty()) {
  1981. std::vector<std::string> options = cmExpandedList(picFlags);
  1982. for (std::string const& o : options) {
  1983. this->AppendFlagEscape(flags, o);
  1984. }
  1985. }
  1986. }
  1987. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  1988. const std::string& var,
  1989. const std::string& config)
  1990. {
  1991. // Add the flags from the variable itself.
  1992. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
  1993. // Add the flags from the build-type specific variable.
  1994. if (!config.empty()) {
  1995. const std::string flagsVar =
  1996. cmStrCat(var, '_', cmSystemTools::UpperCase(config));
  1997. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
  1998. }
  1999. }
  2000. void cmLocalGenerator::AppendFlags(std::string& flags,
  2001. const std::string& newFlags) const
  2002. {
  2003. if (!newFlags.empty()) {
  2004. if (!flags.empty()) {
  2005. flags += " ";
  2006. }
  2007. flags += newFlags;
  2008. }
  2009. }
  2010. void cmLocalGenerator::AppendFlags(
  2011. std::string& flags, const std::vector<BT<std::string>>& newFlags) const
  2012. {
  2013. for (BT<std::string> const& flag : newFlags) {
  2014. this->AppendFlags(flags, flag.Value);
  2015. }
  2016. }
  2017. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  2018. const std::string& rawFlag) const
  2019. {
  2020. this->AppendFlags(flags, this->EscapeForShell(rawFlag));
  2021. }
  2022. void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target,
  2023. const std::string& config)
  2024. {
  2025. const std::string lang = target->GetLinkerLanguage(config);
  2026. const std::string buildType = cmSystemTools::UpperCase(config);
  2027. const std::string pchSource = target->GetPchSource(config, lang);
  2028. const std::string pchHeader = target->GetPchHeader(config, lang);
  2029. if (pchSource.empty() || pchHeader.empty()) {
  2030. return;
  2031. }
  2032. const std::string createOptVar =
  2033. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_CREATE_PCH");
  2034. std::string createOptionList =
  2035. this->Makefile->GetSafeDefinition(createOptVar);
  2036. const std::string useOptVar =
  2037. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_USE_PCH");
  2038. std::string useOptionList = this->Makefile->GetSafeDefinition(useOptVar);
  2039. const std::string pchExtension =
  2040. this->Makefile->GetSafeDefinition("CMAKE_PCH_EXTENSION");
  2041. if (createOptionList.empty() || useOptionList.empty() ||
  2042. pchExtension.empty()) {
  2043. return;
  2044. }
  2045. const char* pchReuseFrom =
  2046. target->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2047. auto pch_sf = this->Makefile->GetOrCreateSource(
  2048. pchSource, false, cmSourceFileLocationKind::Known);
  2049. std::string pchFile = pchHeader;
  2050. if (!this->GetGlobalGenerator()->IsXcode()) {
  2051. if (!pchReuseFrom) {
  2052. target->AddSource(pchSource, true);
  2053. }
  2054. // Exclude the pch files from linking
  2055. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2056. auto replaceExtension = [](const std::string& str,
  2057. const std::string& ext) -> std::string {
  2058. auto dot_pos = str.rfind('.');
  2059. std::string result;
  2060. if (dot_pos != std::string::npos) {
  2061. result = str.substr(0, dot_pos);
  2062. }
  2063. result += ext;
  2064. return result;
  2065. };
  2066. if (!pchReuseFrom) {
  2067. std::string pchSourceObj = target->GetPchFileObject(config, lang);
  2068. pchFile = replaceExtension(pchSourceObj, pchExtension);
  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 =
  2079. cmStrCat(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. cmTarget::PRE_BUILD, no_message, no_current_dir);
  2117. } else {
  2118. cmImplicitDependsList no_implicit_depends;
  2119. cmSourceFile* copy_rule = this->Makefile->AddCustomCommandToOutput(
  2120. outputs, no_byproducts, no_deps, no_main_dependency,
  2121. no_implicit_depends, commandLines, no_message, no_current_dir);
  2122. if (copy_rule) {
  2123. target->AddSource(copy_rule->ResolveFullPath());
  2124. }
  2125. }
  2126. target->Target->SetProperty("COMPILE_PDB_OUTPUT_DIRECTORY",
  2127. target_compile_pdb_dir.c_str());
  2128. }
  2129. std::string pchSourceObj = reuseTarget->GetPchFileObject(config, lang);
  2130. // Link to the pch object file
  2131. target->Target->SetProperty(
  2132. "LINK_FLAGS",
  2133. this->ConvertToOutputFormat(pchSourceObj, SHELL).c_str());
  2134. pchFile = replaceExtension(pchSourceObj, pchExtension);
  2135. }
  2136. } else {
  2137. pchFile += pchExtension;
  2138. pch_sf->SetProperty("PCH_EXTENSION", pchExtension.c_str());
  2139. }
  2140. // Add pchHeader to source files, which will
  2141. // be grouped as "Precompile Header File"
  2142. auto pchHeader_sf = this->Makefile->GetOrCreateSource(
  2143. pchHeader, false, cmSourceFileLocationKind::Known);
  2144. std::string err;
  2145. pchHeader_sf->ResolveFullPath(&err);
  2146. target->AddSource(pchHeader);
  2147. for (auto& str : { std::ref(useOptionList), std::ref(createOptionList) }) {
  2148. cmSystemTools::ReplaceString(str, "<PCH_HEADER>", pchHeader);
  2149. cmSystemTools::ReplaceString(str, "<PCH_FILE>", pchFile);
  2150. }
  2151. }
  2152. pch_sf->SetProperty("COMPILE_OPTIONS", createOptionList.c_str());
  2153. std::vector<cmSourceFile*> sources;
  2154. target->GetSourceFiles(sources, buildType);
  2155. for (cmSourceFile* sf : sources) {
  2156. if (pch_sf == sf || sf->GetLanguage() != lang) {
  2157. continue;
  2158. }
  2159. if (sf->GetPropertyAsBool("SKIP_PRECOMPILE_HEADERS")) {
  2160. if (this->GetGlobalGenerator()->IsXcode()) {
  2161. sf->SetProperty("COMPILE_DEFINITIONS",
  2162. "CMAKE_SKIP_PRECOMPILE_HEADERS");
  2163. }
  2164. continue;
  2165. }
  2166. if (!this->GetGlobalGenerator()->IsXcode()) {
  2167. sf->AppendProperty("OBJECT_DEPENDS", pchFile.c_str());
  2168. sf->AppendProperty("OBJECT_DEPENDS", pchHeader.c_str());
  2169. sf->SetProperty("COMPILE_OPTIONS", useOptionList.c_str());
  2170. }
  2171. }
  2172. }
  2173. void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target,
  2174. const std::string& config)
  2175. {
  2176. if (!target->GetPropertyAsBool("UNITY_BUILD")) {
  2177. return;
  2178. }
  2179. const std::string buildType = cmSystemTools::UpperCase(config);
  2180. std::string filename_base =
  2181. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  2182. target->GetName(), ".dir/Unity/");
  2183. std::vector<cmSourceFile*> sources;
  2184. target->GetSourceFiles(sources, buildType);
  2185. auto batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
  2186. const size_t unityBatchSize =
  2187. static_cast<size_t>(std::atoi(batchSizeString));
  2188. auto beforeInclude = target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
  2189. auto afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
  2190. for (std::string lang : { "C", "CXX" }) {
  2191. std::vector<cmSourceFile*> filtered_sources;
  2192. std::copy_if(sources.begin(), sources.end(),
  2193. std::back_inserter(filtered_sources), [&](cmSourceFile* sf) {
  2194. return sf->GetLanguage() == lang &&
  2195. !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
  2196. !sf->GetPropertyAsBool("GENERATED") &&
  2197. !sf->GetProperty("COMPILE_OPTIONS") &&
  2198. !sf->GetProperty("COMPILE_DEFINITIONS") &&
  2199. !sf->GetProperty("COMPILE_FLAGS") &&
  2200. !sf->GetProperty("INCLUDE_DIRECTORIES");
  2201. });
  2202. size_t batchSize = unityBatchSize;
  2203. if (unityBatchSize == 0) {
  2204. batchSize = filtered_sources.size();
  2205. }
  2206. for (size_t itemsLeft = filtered_sources.size(), chunk = batchSize,
  2207. batch = 0;
  2208. itemsLeft > 0; itemsLeft -= chunk, ++batch) {
  2209. chunk = std::min(itemsLeft, batchSize);
  2210. std::string filename = cmStrCat(filename_base, "unity_", batch,
  2211. (lang == "C") ? ".c" : ".cxx");
  2212. const std::string filename_tmp = cmStrCat(filename, ".tmp");
  2213. {
  2214. size_t begin = batch * batchSize;
  2215. size_t end = begin + chunk;
  2216. cmGeneratedFileStream file(
  2217. filename_tmp, false,
  2218. this->GetGlobalGenerator()->GetMakefileEncoding());
  2219. file << "/* generated by CMake */\n\n";
  2220. for (; begin != end; ++begin) {
  2221. cmSourceFile* sf = filtered_sources[begin];
  2222. // Only in Visual Studio generator we keep the source files
  2223. // for explicit processing. For the rest the source files will
  2224. // not be included in the project.
  2225. if (!this->GetGlobalGenerator()->IsMultiConfig() ||
  2226. this->GetGlobalGenerator()->IsXcode()) {
  2227. sf->SetProperty("HEADER_FILE_ONLY", "ON");
  2228. }
  2229. sf->SetProperty("UNITY_SOURCE_FILE", filename.c_str());
  2230. if (beforeInclude) {
  2231. file << beforeInclude << "\n";
  2232. }
  2233. file << "#include \"" << sf->GetFullPath() << "\"\n";
  2234. if (afterInclude) {
  2235. file << afterInclude << "\n";
  2236. }
  2237. }
  2238. }
  2239. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2240. target->AddSource(filename, true);
  2241. auto unity = this->Makefile->GetOrCreateSource(filename);
  2242. unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
  2243. unity->SetProperty("UNITY_SOURCE_FILE", filename.c_str());
  2244. }
  2245. }
  2246. }
  2247. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  2248. cmGeneratorTarget* target,
  2249. const std::string& config,
  2250. const std::string& lang)
  2251. {
  2252. if (!target->IsIPOEnabled(lang, config)) {
  2253. return;
  2254. }
  2255. switch (target->GetType()) {
  2256. case cmStateEnums::EXECUTABLE:
  2257. case cmStateEnums::SHARED_LIBRARY:
  2258. case cmStateEnums::MODULE_LIBRARY:
  2259. break;
  2260. default:
  2261. return;
  2262. }
  2263. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  2264. const char* rawFlagsList = this->Makefile->GetDefinition(name);
  2265. if (rawFlagsList == nullptr) {
  2266. return;
  2267. }
  2268. std::vector<std::string> flagsList = cmExpandedList(rawFlagsList);
  2269. for (std::string const& o : flagsList) {
  2270. this->AppendFlagEscape(flags, o);
  2271. }
  2272. }
  2273. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  2274. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  2275. const std::string& lang)
  2276. {
  2277. // For now, only EXECUTABLE is concerned
  2278. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  2279. return;
  2280. }
  2281. const char* PICValue = target->GetLinkPIEProperty(config);
  2282. if (PICValue == nullptr) {
  2283. // POSITION_INDEPENDENT_CODE is not set
  2284. return;
  2285. }
  2286. const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
  2287. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  2288. if (cmIsOff(this->Makefile->GetDefinition(supported))) {
  2289. return;
  2290. }
  2291. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  2292. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  2293. if (pieFlags.empty()) {
  2294. return;
  2295. }
  2296. std::vector<std::string> flagsList = cmExpandedList(pieFlags);
  2297. for (const auto& flag : flagsList) {
  2298. this->AppendFlagEscape(flags, flag);
  2299. }
  2300. }
  2301. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  2302. const char* options_list,
  2303. const char* regex) const
  2304. {
  2305. // Short-circuit if there are no options.
  2306. if (!options_list) {
  2307. return;
  2308. }
  2309. // Expand the list of options.
  2310. std::vector<std::string> options_vec = cmExpandedList(options_list);
  2311. this->AppendCompileOptions(options, options_vec, regex);
  2312. }
  2313. void cmLocalGenerator::AppendCompileOptions(
  2314. std::string& options, const std::vector<std::string>& options_vec,
  2315. const char* regex) const
  2316. {
  2317. if (regex != nullptr) {
  2318. // Filter flags upon specified reges.
  2319. cmsys::RegularExpression r(regex);
  2320. for (std::string const& opt : options_vec) {
  2321. if (r.find(opt)) {
  2322. this->AppendFlagEscape(options, opt);
  2323. }
  2324. }
  2325. } else {
  2326. for (std::string const& opt : options_vec) {
  2327. this->AppendFlagEscape(options, opt);
  2328. }
  2329. }
  2330. }
  2331. void cmLocalGenerator::AppendCompileOptions(
  2332. std::vector<BT<std::string>>& options,
  2333. const std::vector<BT<std::string>>& options_vec, const char* regex) const
  2334. {
  2335. if (regex != nullptr) {
  2336. // Filter flags upon specified regular expressions.
  2337. cmsys::RegularExpression r(regex);
  2338. for (BT<std::string> const& opt : options_vec) {
  2339. if (r.find(opt.Value)) {
  2340. std::string flag;
  2341. this->AppendFlagEscape(flag, opt.Value);
  2342. options.emplace_back(std::move(flag), opt.Backtrace);
  2343. }
  2344. }
  2345. } else {
  2346. for (BT<std::string> const& opt : options_vec) {
  2347. std::string flag;
  2348. this->AppendFlagEscape(flag, opt.Value);
  2349. options.emplace_back(std::move(flag), opt.Backtrace);
  2350. }
  2351. }
  2352. }
  2353. void cmLocalGenerator::AppendIncludeDirectories(
  2354. std::vector<std::string>& includes, const char* includes_list,
  2355. const cmSourceFile& sourceFile) const
  2356. {
  2357. // Short-circuit if there are no includes.
  2358. if (!includes_list) {
  2359. return;
  2360. }
  2361. // Expand the list of includes.
  2362. std::vector<std::string> includes_vec = cmExpandedList(includes_list);
  2363. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  2364. }
  2365. void cmLocalGenerator::AppendIncludeDirectories(
  2366. std::vector<std::string>& includes,
  2367. const std::vector<std::string>& includes_vec,
  2368. const cmSourceFile& sourceFile) const
  2369. {
  2370. std::unordered_set<std::string> uniqueIncludes;
  2371. for (const std::string& include : includes_vec) {
  2372. if (!cmSystemTools::FileIsFullPath(include)) {
  2373. std::ostringstream e;
  2374. e << "Found relative path while evaluating include directories of "
  2375. "\""
  2376. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  2377. << "\"\n";
  2378. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2379. return;
  2380. }
  2381. std::string inc = include;
  2382. if (!cmIsOff(inc)) {
  2383. cmSystemTools::ConvertToUnixSlashes(inc);
  2384. }
  2385. if (uniqueIncludes.insert(inc).second) {
  2386. includes.push_back(std::move(inc));
  2387. }
  2388. }
  2389. }
  2390. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  2391. std::string const& defines_list) const
  2392. {
  2393. std::set<BT<std::string>> tmp;
  2394. this->AppendDefines(tmp, ExpandListWithBacktrace(defines_list));
  2395. for (BT<std::string> const& i : tmp) {
  2396. defines.emplace(i.Value);
  2397. }
  2398. }
  2399. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  2400. std::string const& defines_list) const
  2401. {
  2402. // Short-circuit if there are no definitions.
  2403. if (defines_list.empty()) {
  2404. return;
  2405. }
  2406. // Expand the list of definitions.
  2407. this->AppendDefines(defines, ExpandListWithBacktrace(defines_list));
  2408. }
  2409. void cmLocalGenerator::AppendDefines(
  2410. std::set<BT<std::string>>& defines,
  2411. const std::vector<BT<std::string>>& defines_vec) const
  2412. {
  2413. for (BT<std::string> const& d : defines_vec) {
  2414. // Skip unsupported definitions.
  2415. if (!this->CheckDefinition(d.Value)) {
  2416. continue;
  2417. }
  2418. defines.insert(d);
  2419. }
  2420. }
  2421. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  2422. std::string& definesString,
  2423. const std::string& lang)
  2424. {
  2425. // Lookup the define flag for the current language.
  2426. std::string dflag = "-D";
  2427. if (!lang.empty()) {
  2428. const char* df =
  2429. this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
  2430. if (df && *df) {
  2431. dflag = df;
  2432. }
  2433. }
  2434. const char* itemSeparator = definesString.empty() ? "" : " ";
  2435. for (std::string const& define : defines) {
  2436. // Append the definition with proper escaping.
  2437. std::string def = dflag;
  2438. if (this->GetState()->UseWatcomWMake()) {
  2439. // The Watcom compiler does its own command line parsing instead
  2440. // of using the windows shell rules. Definitions are one of
  2441. // -DNAME
  2442. // -DNAME=<cpp-token>
  2443. // -DNAME="c-string with spaces and other characters(?@#$)"
  2444. //
  2445. // Watcom will properly parse each of these cases from the
  2446. // command line without any escapes. However we still have to
  2447. // get the '$' and '#' characters through WMake as '$$' and
  2448. // '$#'.
  2449. for (const char* c = define.c_str(); *c; ++c) {
  2450. if (*c == '$' || *c == '#') {
  2451. def += '$';
  2452. }
  2453. def += *c;
  2454. }
  2455. } else {
  2456. // Make the definition appear properly on the command line. Use
  2457. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  2458. std::string::size_type eq = define.find('=');
  2459. def += define.substr(0, eq);
  2460. if (eq != std::string::npos) {
  2461. def += "=";
  2462. def += this->EscapeForShell(define.substr(eq + 1), true);
  2463. }
  2464. }
  2465. definesString += itemSeparator;
  2466. itemSeparator = " ";
  2467. definesString += def;
  2468. }
  2469. }
  2470. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  2471. const std::string& lang,
  2472. const char* feature)
  2473. {
  2474. const char* optionList = this->Makefile->GetDefinition(
  2475. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
  2476. if (optionList != nullptr) {
  2477. std::vector<std::string> options = cmExpandedList(optionList);
  2478. for (std::string const& o : options) {
  2479. this->AppendFlagEscape(flags, o);
  2480. }
  2481. }
  2482. }
  2483. const char* cmLocalGenerator::GetFeature(const std::string& feature,
  2484. const std::string& config)
  2485. {
  2486. std::string featureName = feature;
  2487. // TODO: Define accumulation policy for features (prepend, append, replace).
  2488. // Currently we always replace.
  2489. if (!config.empty()) {
  2490. featureName += "_";
  2491. featureName += cmSystemTools::UpperCase(config);
  2492. }
  2493. cmStateSnapshot snp = this->StateSnapshot;
  2494. while (snp.IsValid()) {
  2495. if (const char* value = snp.GetDirectory().GetProperty(featureName)) {
  2496. return value;
  2497. }
  2498. snp = snp.GetBuildsystemDirectoryParent();
  2499. }
  2500. return nullptr;
  2501. }
  2502. std::string cmLocalGenerator::GetProjectName() const
  2503. {
  2504. return this->StateSnapshot.GetProjectName();
  2505. }
  2506. std::string cmLocalGenerator::ConstructComment(
  2507. cmCustomCommandGenerator const& ccg, const char* default_comment)
  2508. {
  2509. // Check for a comment provided with the command.
  2510. if (ccg.GetComment()) {
  2511. return ccg.GetComment();
  2512. }
  2513. // Construct a reasonable default comment if possible.
  2514. if (!ccg.GetOutputs().empty()) {
  2515. std::string comment;
  2516. comment = "Generating ";
  2517. const char* sep = "";
  2518. std::string currentBinaryDir = this->GetCurrentBinaryDirectory();
  2519. for (std::string const& o : ccg.GetOutputs()) {
  2520. comment += sep;
  2521. comment += this->MaybeConvertToRelativePath(currentBinaryDir, o);
  2522. sep = ", ";
  2523. }
  2524. return comment;
  2525. }
  2526. // Otherwise use the provided default.
  2527. return default_comment;
  2528. }
  2529. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  2530. {
  2531. public:
  2532. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  2533. const char* dest, bool implib)
  2534. : cmInstallTargetGenerator(
  2535. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  2536. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  2537. false)
  2538. {
  2539. this->Compute(lg);
  2540. }
  2541. };
  2542. void cmLocalGenerator::GenerateTargetInstallRules(
  2543. std::ostream& os, const std::string& config,
  2544. std::vector<std::string> const& configurationTypes)
  2545. {
  2546. // Convert the old-style install specification from each target to
  2547. // an install generator and run it.
  2548. const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
  2549. for (cmGeneratorTarget* l : tgts) {
  2550. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2551. continue;
  2552. }
  2553. // Include the user-specified pre-install script for this target.
  2554. if (const char* preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  2555. cmInstallScriptGenerator g(preinstall, false, nullptr, false);
  2556. g.Generate(os, config, configurationTypes);
  2557. }
  2558. // Install this target if a destination is given.
  2559. if (!l->Target->GetInstallPath().empty()) {
  2560. // Compute the full install destination. Note that converting
  2561. // to unix slashes also removes any trailing slash.
  2562. // We also skip over the leading slash given by the user.
  2563. std::string destination = l->Target->GetInstallPath().substr(1);
  2564. cmSystemTools::ConvertToUnixSlashes(destination);
  2565. if (destination.empty()) {
  2566. destination = ".";
  2567. }
  2568. // Generate the proper install generator for this target type.
  2569. switch (l->GetType()) {
  2570. case cmStateEnums::EXECUTABLE:
  2571. case cmStateEnums::STATIC_LIBRARY:
  2572. case cmStateEnums::MODULE_LIBRARY: {
  2573. // Use a target install generator.
  2574. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2575. destination.c_str(), false);
  2576. g.Generate(os, config, configurationTypes);
  2577. } break;
  2578. case cmStateEnums::SHARED_LIBRARY: {
  2579. #if defined(_WIN32) || defined(__CYGWIN__)
  2580. // Special code to handle DLL. Install the import library
  2581. // to the normal destination and the DLL to the runtime
  2582. // destination.
  2583. cmInstallTargetGeneratorLocal g1(this, l->GetName(),
  2584. destination.c_str(), true);
  2585. g1.Generate(os, config, configurationTypes);
  2586. // We also skip over the leading slash given by the user.
  2587. destination = l->Target->GetRuntimeInstallPath().substr(1);
  2588. cmSystemTools::ConvertToUnixSlashes(destination);
  2589. cmInstallTargetGeneratorLocal g2(this, l->GetName(),
  2590. destination.c_str(), false);
  2591. g2.Generate(os, config, configurationTypes);
  2592. #else
  2593. // Use a target install generator.
  2594. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2595. destination.c_str(), false);
  2596. g.Generate(os, config, configurationTypes);
  2597. #endif
  2598. } break;
  2599. default:
  2600. break;
  2601. }
  2602. }
  2603. // Include the user-specified post-install script for this target.
  2604. if (const char* postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  2605. cmInstallScriptGenerator g(postinstall, false, nullptr, false);
  2606. g.Generate(os, config, configurationTypes);
  2607. }
  2608. }
  2609. }
  2610. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2611. static bool cmLocalGeneratorShortenObjectName(std::string& objName,
  2612. std::string::size_type max_len)
  2613. {
  2614. // Replace the beginning of the path portion of the object name with
  2615. // its own md5 sum.
  2616. std::string::size_type pos =
  2617. objName.find('/', objName.size() - max_len + 32);
  2618. if (pos != std::string::npos) {
  2619. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  2620. std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
  2621. cm::string_view(objName).substr(pos));
  2622. objName = md5name;
  2623. // The object name is now short enough.
  2624. return true;
  2625. }
  2626. // The object name could not be shortened enough.
  2627. return false;
  2628. }
  2629. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  2630. std::string::size_type dir_len,
  2631. std::string::size_type max_total_len)
  2632. {
  2633. // Enforce the maximum file name length if possible.
  2634. std::string::size_type max_obj_len = max_total_len;
  2635. if (dir_len < max_total_len) {
  2636. max_obj_len = max_total_len - dir_len;
  2637. if (objName.size() > max_obj_len) {
  2638. // The current object file name is too long. Try to shorten it.
  2639. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  2640. }
  2641. // The object file name is short enough.
  2642. return true;
  2643. }
  2644. // The build directory in which the object will be stored is
  2645. // already too deep.
  2646. return false;
  2647. }
  2648. #endif
  2649. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  2650. const std::string& sin, std::string const& dir_max)
  2651. {
  2652. // Look for an existing mapped name for this object file.
  2653. auto it = this->UniqueObjectNamesMap.find(sin);
  2654. // If no entry exists create one.
  2655. if (it == this->UniqueObjectNamesMap.end()) {
  2656. // Start with the original name.
  2657. std::string ssin = sin;
  2658. // Avoid full paths by removing leading slashes.
  2659. ssin.erase(0, ssin.find_first_not_of('/'));
  2660. // Avoid full paths by removing colons.
  2661. std::replace(ssin.begin(), ssin.end(), ':', '_');
  2662. // Avoid relative paths that go up the tree.
  2663. cmSystemTools::ReplaceString(ssin, "../", "__/");
  2664. // Avoid spaces.
  2665. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  2666. // Mangle the name if necessary.
  2667. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  2668. bool done;
  2669. int cc = 0;
  2670. char rpstr[100];
  2671. sprintf(rpstr, "_p_");
  2672. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  2673. std::string sssin = sin;
  2674. do {
  2675. done = true;
  2676. for (it = this->UniqueObjectNamesMap.begin();
  2677. it != this->UniqueObjectNamesMap.end(); ++it) {
  2678. if (it->second == ssin) {
  2679. done = false;
  2680. }
  2681. }
  2682. if (done) {
  2683. break;
  2684. }
  2685. sssin = ssin;
  2686. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  2687. sprintf(rpstr, "_p%d_", cc++);
  2688. } while (!done);
  2689. }
  2690. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2691. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  2692. this->ObjectPathMax)) {
  2693. // Warn if this is the first time the path has been seen.
  2694. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  2695. std::ostringstream m;
  2696. /* clang-format off */
  2697. m << "The object file directory\n"
  2698. << " " << dir_max << "\n"
  2699. << "has " << dir_max.size() << " characters. "
  2700. << "The maximum full path to an object file is "
  2701. << this->ObjectPathMax << " characters "
  2702. << "(see CMAKE_OBJECT_PATH_MAX). "
  2703. << "Object file\n"
  2704. << " " << ssin << "\n"
  2705. << "cannot be safely placed under this directory. "
  2706. << "The build may not work correctly.";
  2707. /* clang-format on */
  2708. this->IssueMessage(MessageType::WARNING, m.str());
  2709. }
  2710. }
  2711. #else
  2712. (void)dir_max;
  2713. #endif
  2714. // Insert the newly mapped object file name.
  2715. std::map<std::string, std::string>::value_type e(sin, ssin);
  2716. it = this->UniqueObjectNamesMap.insert(e).first;
  2717. }
  2718. // Return the map entry.
  2719. return it->second;
  2720. }
  2721. void cmLocalGenerator::ComputeObjectFilenames(
  2722. std::map<cmSourceFile const*, std::string>& /*unused*/,
  2723. cmGeneratorTarget const* /*unused*/)
  2724. {
  2725. }
  2726. bool cmLocalGenerator::IsWindowsShell() const
  2727. {
  2728. return this->GetState()->UseWindowsShell();
  2729. }
  2730. bool cmLocalGenerator::IsWatcomWMake() const
  2731. {
  2732. return this->GetState()->UseWatcomWMake();
  2733. }
  2734. bool cmLocalGenerator::IsMinGWMake() const
  2735. {
  2736. return this->GetState()->UseMinGWMake();
  2737. }
  2738. bool cmLocalGenerator::IsNMake() const
  2739. {
  2740. return this->GetState()->UseNMake();
  2741. }
  2742. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  2743. const cmSourceFile& source, std::string const& dir_max,
  2744. bool* hasSourceExtension, char const* customOutputExtension)
  2745. {
  2746. // Construct the object file name using the full path to the source
  2747. // file which is its only unique identification.
  2748. std::string const& fullPath = source.GetFullPath();
  2749. // Try referencing the source relative to the source tree.
  2750. std::string relFromSource = this->MaybeConvertToRelativePath(
  2751. this->GetCurrentSourceDirectory(), fullPath);
  2752. assert(!relFromSource.empty());
  2753. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  2754. bool subSource = relSource && relFromSource[0] != '.';
  2755. // Try referencing the source relative to the binary tree.
  2756. std::string relFromBinary = this->MaybeConvertToRelativePath(
  2757. this->GetCurrentBinaryDirectory(), fullPath);
  2758. assert(!relFromBinary.empty());
  2759. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  2760. bool subBinary = relBinary && relFromBinary[0] != '.';
  2761. // Select a nice-looking reference to the source file to construct
  2762. // the object file name.
  2763. std::string objectName;
  2764. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  2765. objectName = relFromSource;
  2766. } else if ((relBinary && !relSource) || (subBinary && !subSource)) {
  2767. objectName = relFromBinary;
  2768. } else if (relFromBinary.length() < relFromSource.length()) {
  2769. objectName = relFromBinary;
  2770. } else {
  2771. objectName = relFromSource;
  2772. }
  2773. // if it is still a full path check for the try compile case
  2774. // try compile never have in source sources, and should not
  2775. // have conflicting source file names in the same target
  2776. if (cmSystemTools::FileIsFullPath(objectName)) {
  2777. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  2778. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  2779. }
  2780. }
  2781. // Replace the original source file extension with the object file
  2782. // extension.
  2783. bool keptSourceExtension = true;
  2784. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  2785. // Decide whether this language wants to replace the source
  2786. // extension with the object extension. For CMake 2.4
  2787. // compatibility do this by default.
  2788. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  2789. if (!replaceExt) {
  2790. std::string lang = source.GetLanguage();
  2791. if (!lang.empty()) {
  2792. replaceExt = this->Makefile->IsOn(
  2793. cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
  2794. }
  2795. }
  2796. const char* pchExtension = source.GetProperty("PCH_EXTENSION");
  2797. if (pchExtension) {
  2798. customOutputExtension = pchExtension;
  2799. }
  2800. // Remove the source extension if it is to be replaced.
  2801. if (replaceExt || customOutputExtension) {
  2802. keptSourceExtension = false;
  2803. std::string::size_type dot_pos = objectName.rfind('.');
  2804. if (dot_pos != std::string::npos) {
  2805. objectName = objectName.substr(0, dot_pos);
  2806. }
  2807. }
  2808. // Store the new extension.
  2809. if (customOutputExtension) {
  2810. objectName += customOutputExtension;
  2811. } else {
  2812. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  2813. }
  2814. }
  2815. if (hasSourceExtension) {
  2816. *hasSourceExtension = keptSourceExtension;
  2817. }
  2818. // Convert to a safe name.
  2819. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  2820. }
  2821. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  2822. {
  2823. return source.GetLanguage();
  2824. }
  2825. cmake* cmLocalGenerator::GetCMakeInstance() const
  2826. {
  2827. return this->GlobalGenerator->GetCMakeInstance();
  2828. }
  2829. std::string const& cmLocalGenerator::GetSourceDirectory() const
  2830. {
  2831. return this->GetCMakeInstance()->GetHomeDirectory();
  2832. }
  2833. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  2834. {
  2835. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  2836. }
  2837. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  2838. {
  2839. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  2840. }
  2841. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  2842. {
  2843. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  2844. }
  2845. std::string cmLocalGenerator::MaybeConvertToRelativePath(
  2846. std::string const& local_path, std::string const& remote_path) const
  2847. {
  2848. return this->StateSnapshot.GetDirectory().ConvertToRelPathIfNotContained(
  2849. local_path, remote_path);
  2850. }
  2851. std::string cmLocalGenerator::GetTargetDirectory(
  2852. const cmGeneratorTarget* /*unused*/) const
  2853. {
  2854. cmSystemTools::Error("GetTargetDirectory"
  2855. " called on cmLocalGenerator");
  2856. return "";
  2857. }
  2858. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  2859. {
  2860. // The computed version may change until the project is fully
  2861. // configured.
  2862. if (!this->BackwardsCompatibilityFinal) {
  2863. unsigned int major = 0;
  2864. unsigned int minor = 0;
  2865. unsigned int patch = 0;
  2866. if (const char* value =
  2867. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  2868. switch (sscanf(value, "%u.%u.%u", &major, &minor, &patch)) {
  2869. case 2:
  2870. patch = 0;
  2871. break;
  2872. case 1:
  2873. minor = 0;
  2874. patch = 0;
  2875. break;
  2876. default:
  2877. break;
  2878. }
  2879. }
  2880. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  2881. this->BackwardsCompatibilityFinal = true;
  2882. }
  2883. return this->BackwardsCompatibility;
  2884. }
  2885. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  2886. {
  2887. // Check the policy to decide whether to pay attention to this
  2888. // variable.
  2889. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  2890. case cmPolicies::WARN:
  2891. // WARN is just OLD without warning because user code does not
  2892. // always affect whether this check is done.
  2893. case cmPolicies::OLD:
  2894. // Old behavior is to check the variable.
  2895. break;
  2896. case cmPolicies::NEW:
  2897. // New behavior is to ignore the variable.
  2898. return false;
  2899. case cmPolicies::REQUIRED_IF_USED:
  2900. case cmPolicies::REQUIRED_ALWAYS:
  2901. // This will never be the case because the only way to require
  2902. // the setting is to require the user to specify version policy
  2903. // 2.6 or higher. Once we add that requirement then this whole
  2904. // method can be removed anyway.
  2905. return false;
  2906. }
  2907. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  2908. // equal to or lower than the given version.
  2909. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  2910. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  2911. }
  2912. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  2913. cmPolicies::PolicyID id) const
  2914. {
  2915. return this->Makefile->GetPolicyStatus(id);
  2916. }
  2917. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  2918. {
  2919. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  2920. std::string::size_type pos = define.find_first_of("(=");
  2921. if (pos != std::string::npos) {
  2922. if (define[pos] == '(') {
  2923. std::ostringstream e;
  2924. /* clang-format off */
  2925. e << "WARNING: Function-style preprocessor definitions may not be "
  2926. << "passed on the compiler command line because many compilers "
  2927. << "do not support it.\n"
  2928. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2929. << "Consider defining the macro in a (configured) header file.\n";
  2930. /* clang-format on */
  2931. cmSystemTools::Message(e.str());
  2932. return false;
  2933. }
  2934. }
  2935. // Many compilers do not support # in the value so we disable it.
  2936. if (define.find_first_of('#') != std::string::npos) {
  2937. std::ostringstream e;
  2938. /* clang-format off */
  2939. e << "WARNING: Preprocessor definitions containing '#' may not be "
  2940. << "passed on the compiler command line because many compilers "
  2941. << "do not support it.\n"
  2942. << "CMake is dropping a preprocessor definition: " << define << "\n"
  2943. << "Consider defining the macro in a (configured) header file.\n";
  2944. /* clang-format on */
  2945. cmSystemTools::Message(e.str());
  2946. return false;
  2947. }
  2948. // Assume it is supported.
  2949. return true;
  2950. }
  2951. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  2952. const std::string& prop)
  2953. {
  2954. if (const char* val = target->GetProperty(prop)) {
  2955. mf->AddDefinition(prop, val);
  2956. }
  2957. }
  2958. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  2959. const std::string& targetName,
  2960. const std::string& fname)
  2961. {
  2962. // Find the Info.plist template.
  2963. const char* in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  2964. std::string inFile = (in && *in) ? in : "MacOSXBundleInfo.plist.in";
  2965. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2966. std::string inMod = this->Makefile->GetModulesFile(inFile);
  2967. if (!inMod.empty()) {
  2968. inFile = inMod;
  2969. }
  2970. }
  2971. if (!cmSystemTools::FileExists(inFile, true)) {
  2972. std::ostringstream e;
  2973. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  2974. << "\" could not be found.";
  2975. cmSystemTools::Error(e.str());
  2976. return;
  2977. }
  2978. // Convert target properties to variables in an isolated makefile
  2979. // scope to configure the file. If properties are set they will
  2980. // override user make variables. If not the configuration will fall
  2981. // back to the directory-level values set by the user.
  2982. cmMakefile* mf = this->Makefile;
  2983. cmMakefile::ScopePushPop varScope(mf);
  2984. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
  2985. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  2986. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  2987. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  2988. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  2989. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  2990. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  2991. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  2992. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  2993. mf->ConfigureFile(inFile, fname, false, false, false);
  2994. }
  2995. void cmLocalGenerator::GenerateFrameworkInfoPList(
  2996. cmGeneratorTarget* target, const std::string& targetName,
  2997. const std::string& fname)
  2998. {
  2999. // Find the Info.plist template.
  3000. const char* in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  3001. std::string inFile = (in && *in) ? in : "MacOSXFrameworkInfo.plist.in";
  3002. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3003. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3004. if (!inMod.empty()) {
  3005. inFile = inMod;
  3006. }
  3007. }
  3008. if (!cmSystemTools::FileExists(inFile, true)) {
  3009. std::ostringstream e;
  3010. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3011. << "\" could not be found.";
  3012. cmSystemTools::Error(e.str());
  3013. return;
  3014. }
  3015. // Convert target properties to variables in an isolated makefile
  3016. // scope to configure the file. If properties are set they will
  3017. // override user make variables. If not the configuration will fall
  3018. // back to the directory-level values set by the user.
  3019. cmMakefile* mf = this->Makefile;
  3020. cmMakefile::ScopePushPop varScope(mf);
  3021. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
  3022. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  3023. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  3024. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  3025. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  3026. mf->ConfigureFile(inFile, fname, false, false, false);
  3027. }