cmLocalGenerator.cxx 116 KB

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