cmLocalGenerator.cxx 116 KB

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