cmMakefileTargetGenerator.cxx 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827
  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 "cmMakefileTargetGenerator.h"
  4. #include <cassert>
  5. #include <cstdio>
  6. #include <sstream>
  7. #include <utility>
  8. #include <cm/memory>
  9. #include <cmext/algorithm>
  10. #include "cmComputeLinkInformation.h"
  11. #include "cmCustomCommand.h"
  12. #include "cmCustomCommandGenerator.h"
  13. #include "cmGeneratedFileStream.h"
  14. #include "cmGeneratorExpression.h"
  15. #include "cmGeneratorTarget.h"
  16. #include "cmGlobalUnixMakefileGenerator3.h"
  17. #include "cmLinkLineComputer.h"
  18. #include "cmLocalCommonGenerator.h"
  19. #include "cmLocalUnixMakefileGenerator3.h"
  20. #include "cmMakefile.h"
  21. #include "cmMakefileExecutableTargetGenerator.h"
  22. #include "cmMakefileLibraryTargetGenerator.h"
  23. #include "cmMakefileUtilityTargetGenerator.h"
  24. #include "cmOutputConverter.h"
  25. #include "cmRange.h"
  26. #include "cmRulePlaceholderExpander.h"
  27. #include "cmSourceFile.h"
  28. #include "cmState.h"
  29. #include "cmStateDirectory.h"
  30. #include "cmStateSnapshot.h"
  31. #include "cmStateTypes.h"
  32. #include "cmStringAlgorithms.h"
  33. #include "cmSystemTools.h"
  34. #include "cmake.h"
  35. cmMakefileTargetGenerator::cmMakefileTargetGenerator(cmGeneratorTarget* target)
  36. : cmCommonTargetGenerator(target)
  37. {
  38. this->CustomCommandDriver = OnBuild;
  39. this->LocalGenerator =
  40. static_cast<cmLocalUnixMakefileGenerator3*>(target->GetLocalGenerator());
  41. this->GlobalGenerator = static_cast<cmGlobalUnixMakefileGenerator3*>(
  42. this->LocalGenerator->GetGlobalGenerator());
  43. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  44. this->NoRuleMessages = false;
  45. if (const char* ruleStatus =
  46. cm->GetState()->GetGlobalProperty("RULE_MESSAGES")) {
  47. this->NoRuleMessages = cmIsOff(ruleStatus);
  48. }
  49. MacOSXContentGenerator = cm::make_unique<MacOSXContentGeneratorType>(this);
  50. }
  51. cmMakefileTargetGenerator::~cmMakefileTargetGenerator() = default;
  52. std::unique_ptr<cmMakefileTargetGenerator> cmMakefileTargetGenerator::New(
  53. cmGeneratorTarget* tgt)
  54. {
  55. std::unique_ptr<cmMakefileTargetGenerator> result;
  56. switch (tgt->GetType()) {
  57. case cmStateEnums::EXECUTABLE:
  58. result = cm::make_unique<cmMakefileExecutableTargetGenerator>(tgt);
  59. break;
  60. case cmStateEnums::STATIC_LIBRARY:
  61. case cmStateEnums::SHARED_LIBRARY:
  62. case cmStateEnums::MODULE_LIBRARY:
  63. case cmStateEnums::OBJECT_LIBRARY:
  64. result = cm::make_unique<cmMakefileLibraryTargetGenerator>(tgt);
  65. break;
  66. case cmStateEnums::UTILITY:
  67. result = cm::make_unique<cmMakefileUtilityTargetGenerator>(tgt);
  68. break;
  69. default:
  70. return result;
  71. // break; /* unreachable */
  72. }
  73. return result;
  74. }
  75. std::string cmMakefileTargetGenerator::GetConfigName()
  76. {
  77. auto const& configNames = this->LocalGenerator->GetConfigNames();
  78. assert(configNames.size() == 1);
  79. return configNames.front();
  80. }
  81. void cmMakefileTargetGenerator::GetTargetLinkFlags(
  82. std::string& flags, const std::string& linkLanguage)
  83. {
  84. this->LocalGenerator->AppendFlags(
  85. flags, this->GeneratorTarget->GetSafeProperty("LINK_FLAGS"));
  86. std::string linkFlagsConfig =
  87. cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(this->GetConfigName()));
  88. this->LocalGenerator->AppendFlags(
  89. flags, this->GeneratorTarget->GetSafeProperty(linkFlagsConfig));
  90. std::vector<std::string> opts;
  91. this->GeneratorTarget->GetLinkOptions(opts, this->GetConfigName(),
  92. linkLanguage);
  93. // LINK_OPTIONS are escaped.
  94. this->LocalGenerator->AppendCompileOptions(flags, opts);
  95. this->LocalGenerator->AppendPositionIndependentLinkerFlags(
  96. flags, this->GeneratorTarget, this->GetConfigName(), linkLanguage);
  97. }
  98. void cmMakefileTargetGenerator::CreateRuleFile()
  99. {
  100. // Create a directory for this target.
  101. this->TargetBuildDirectory =
  102. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  103. this->TargetBuildDirectoryFull =
  104. this->LocalGenerator->ConvertToFullPath(this->TargetBuildDirectory);
  105. cmSystemTools::MakeDirectory(this->TargetBuildDirectoryFull);
  106. // Construct the rule file name.
  107. this->BuildFileName = cmStrCat(this->TargetBuildDirectory, "/build.make");
  108. this->BuildFileNameFull =
  109. cmStrCat(this->TargetBuildDirectoryFull, "/build.make");
  110. // Construct the rule file name.
  111. this->ProgressFileNameFull =
  112. cmStrCat(this->TargetBuildDirectoryFull, "/progress.make");
  113. // reset the progress count
  114. this->NumberOfProgressActions = 0;
  115. // Open the rule file. This should be copy-if-different because the
  116. // rules may depend on this file itself.
  117. this->BuildFileStream = cm::make_unique<cmGeneratedFileStream>(
  118. this->BuildFileNameFull, false,
  119. this->GlobalGenerator->GetMakefileEncoding());
  120. if (!this->BuildFileStream) {
  121. return;
  122. }
  123. this->BuildFileStream->SetCopyIfDifferent(true);
  124. this->LocalGenerator->WriteDisclaimer(*this->BuildFileStream);
  125. if (this->GlobalGenerator->AllowDeleteOnError()) {
  126. std::vector<std::string> no_depends;
  127. std::vector<std::string> no_commands;
  128. this->LocalGenerator->WriteMakeRule(
  129. *this->BuildFileStream, "Delete rule output on recipe failure.",
  130. ".DELETE_ON_ERROR", no_depends, no_commands, false);
  131. }
  132. this->LocalGenerator->WriteSpecialTargetsTop(*this->BuildFileStream);
  133. }
  134. void cmMakefileTargetGenerator::WriteTargetBuildRules()
  135. {
  136. // -- Write the custom commands for this target
  137. // Evaluates generator expressions and expands prop_value
  138. auto evaluatedFiles =
  139. [this](const char* prop_value) -> std::vector<std::string> {
  140. std::vector<std::string> files;
  141. cmExpandList(cmGeneratorExpression::Evaluate(
  142. prop_value, this->LocalGenerator, this->GetConfigName(),
  143. this->GeneratorTarget),
  144. files);
  145. return files;
  146. };
  147. // Look for additional files registered for cleaning in this directory.
  148. if (const char* prop_value =
  149. this->Makefile->GetProperty("ADDITIONAL_MAKE_CLEAN_FILES")) {
  150. std::vector<std::string> const files = evaluatedFiles(prop_value);
  151. this->CleanFiles.insert(files.begin(), files.end());
  152. }
  153. // Look for additional files registered for cleaning in this target.
  154. if (const char* prop_value =
  155. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  156. std::vector<std::string> const files = evaluatedFiles(prop_value);
  157. // For relative path support
  158. std::string const& binaryDir =
  159. this->LocalGenerator->GetCurrentBinaryDirectory();
  160. for (std::string const& cfl : files) {
  161. this->CleanFiles.insert(cmSystemTools::CollapseFullPath(cfl, binaryDir));
  162. }
  163. }
  164. // add custom commands to the clean rules?
  165. const char* clean_no_custom = this->Makefile->GetProperty("CLEAN_NO_CUSTOM");
  166. bool clean = cmIsOff(clean_no_custom);
  167. // First generate the object rule files. Save a list of all object
  168. // files for this target.
  169. std::vector<cmSourceFile const*> customCommands;
  170. this->GeneratorTarget->GetCustomCommands(customCommands,
  171. this->GetConfigName());
  172. std::string currentBinDir =
  173. this->LocalGenerator->GetCurrentBinaryDirectory();
  174. for (cmSourceFile const* sf : customCommands) {
  175. cmCustomCommandGenerator ccg(*sf->GetCustomCommand(),
  176. this->GetConfigName(), this->LocalGenerator);
  177. this->GenerateCustomRuleFile(ccg);
  178. if (clean) {
  179. const std::vector<std::string>& outputs = ccg.GetOutputs();
  180. for (std::string const& output : outputs) {
  181. this->CleanFiles.insert(
  182. this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir,
  183. output));
  184. }
  185. const std::vector<std::string>& byproducts = ccg.GetByproducts();
  186. for (std::string const& byproduct : byproducts) {
  187. this->CleanFiles.insert(
  188. this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir,
  189. byproduct));
  190. }
  191. }
  192. }
  193. // Add byproducts from build events to the clean rules
  194. if (clean) {
  195. std::vector<cmCustomCommand> buildEventCommands =
  196. this->GeneratorTarget->GetPreBuildCommands();
  197. cm::append(buildEventCommands,
  198. this->GeneratorTarget->GetPreLinkCommands());
  199. cm::append(buildEventCommands,
  200. this->GeneratorTarget->GetPostBuildCommands());
  201. for (const auto& be : buildEventCommands) {
  202. cmCustomCommandGenerator beg(be, this->GetConfigName(),
  203. this->LocalGenerator);
  204. const std::vector<std::string>& byproducts = beg.GetByproducts();
  205. for (std::string const& byproduct : byproducts) {
  206. this->CleanFiles.insert(
  207. this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir,
  208. byproduct));
  209. }
  210. }
  211. }
  212. std::vector<cmSourceFile const*> headerSources;
  213. this->GeneratorTarget->GetHeaderSources(headerSources,
  214. this->GetConfigName());
  215. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  216. headerSources, this->MacOSXContentGenerator.get(), this->GetConfigName());
  217. std::vector<cmSourceFile const*> extraSources;
  218. this->GeneratorTarget->GetExtraSources(extraSources, this->GetConfigName());
  219. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  220. extraSources, this->MacOSXContentGenerator.get(), this->GetConfigName());
  221. const char* pchExtension =
  222. this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  223. std::vector<cmSourceFile const*> externalObjects;
  224. this->GeneratorTarget->GetExternalObjects(externalObjects,
  225. this->GetConfigName());
  226. for (cmSourceFile const* sf : externalObjects) {
  227. auto const& objectFileName = sf->GetFullPath();
  228. if (!cmSystemTools::StringEndsWith(objectFileName, pchExtension)) {
  229. this->ExternalObjects.push_back(objectFileName);
  230. }
  231. }
  232. std::vector<cmSourceFile const*> objectSources;
  233. this->GeneratorTarget->GetObjectSources(objectSources,
  234. this->GetConfigName());
  235. for (cmSourceFile const* sf : objectSources) {
  236. // Generate this object file's rule file.
  237. this->WriteObjectRuleFiles(*sf);
  238. }
  239. }
  240. void cmMakefileTargetGenerator::WriteCommonCodeRules()
  241. {
  242. const char* root = (this->Makefile->IsOn("CMAKE_MAKE_INCLUDE_FROM_ROOT")
  243. ? "$(CMAKE_BINARY_DIR)/"
  244. : "");
  245. // Include the dependencies for the target.
  246. std::string dependFileNameFull =
  247. cmStrCat(this->TargetBuildDirectoryFull, "/depend.make");
  248. *this->BuildFileStream
  249. << "# Include any dependencies generated for this target.\n"
  250. << this->GlobalGenerator->IncludeDirective << " " << root
  251. << cmSystemTools::ConvertToOutputPath(
  252. this->LocalGenerator->MaybeConvertToRelativePath(
  253. this->LocalGenerator->GetBinaryDirectory(), dependFileNameFull))
  254. << "\n\n";
  255. if (!this->NoRuleMessages) {
  256. // Include the progress variables for the target.
  257. *this->BuildFileStream
  258. << "# Include the progress variables for this target.\n"
  259. << this->GlobalGenerator->IncludeDirective << " " << root
  260. << cmSystemTools::ConvertToOutputPath(
  261. this->LocalGenerator->MaybeConvertToRelativePath(
  262. this->LocalGenerator->GetBinaryDirectory(),
  263. this->ProgressFileNameFull))
  264. << "\n\n";
  265. }
  266. // make sure the depend file exists
  267. if (!cmSystemTools::FileExists(dependFileNameFull)) {
  268. // Write an empty dependency file.
  269. cmGeneratedFileStream depFileStream(
  270. dependFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
  271. depFileStream << "# Empty dependencies file for "
  272. << this->GeneratorTarget->GetName() << ".\n"
  273. << "# This may be replaced when dependencies are built."
  274. << std::endl;
  275. }
  276. // Open the flags file. This should be copy-if-different because the
  277. // rules may depend on this file itself.
  278. this->FlagFileNameFull =
  279. cmStrCat(this->TargetBuildDirectoryFull, "/flags.make");
  280. this->FlagFileStream = cm::make_unique<cmGeneratedFileStream>(
  281. this->FlagFileNameFull, false,
  282. this->GlobalGenerator->GetMakefileEncoding());
  283. if (!this->FlagFileStream) {
  284. return;
  285. }
  286. this->FlagFileStream->SetCopyIfDifferent(true);
  287. this->LocalGenerator->WriteDisclaimer(*this->FlagFileStream);
  288. // Include the flags for the target.
  289. *this->BuildFileStream
  290. << "# Include the compile flags for this target's objects.\n"
  291. << this->GlobalGenerator->IncludeDirective << " " << root
  292. << cmSystemTools::ConvertToOutputPath(
  293. this->LocalGenerator->MaybeConvertToRelativePath(
  294. this->LocalGenerator->GetBinaryDirectory(), this->FlagFileNameFull))
  295. << "\n\n";
  296. }
  297. void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
  298. {
  299. // write language flags for target
  300. std::set<std::string> languages;
  301. this->GeneratorTarget->GetLanguages(
  302. languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  303. // put the compiler in the rules.make file so that if it changes
  304. // things rebuild
  305. for (std::string const& language : languages) {
  306. std::string compiler = cmStrCat("CMAKE_", language, "_COMPILER");
  307. *this->FlagFileStream << "# compile " << language << " with "
  308. << this->Makefile->GetSafeDefinition(compiler)
  309. << "\n";
  310. }
  311. for (std::string const& language : languages) {
  312. std::string flags = this->GetFlags(language, this->GetConfigName());
  313. std::string defines = this->GetDefines(language, this->GetConfigName());
  314. std::string includes = this->GetIncludes(language, this->GetConfigName());
  315. // Escape comment characters so they do not terminate assignment.
  316. cmSystemTools::ReplaceString(flags, "#", "\\#");
  317. cmSystemTools::ReplaceString(defines, "#", "\\#");
  318. cmSystemTools::ReplaceString(includes, "#", "\\#");
  319. *this->FlagFileStream << language << "_FLAGS = " << flags << "\n\n";
  320. *this->FlagFileStream << language << "_DEFINES = " << defines << "\n\n";
  321. *this->FlagFileStream << language << "_INCLUDES = " << includes << "\n\n";
  322. }
  323. }
  324. void cmMakefileTargetGenerator::MacOSXContentGeneratorType::operator()(
  325. cmSourceFile const& source, const char* pkgloc, const std::string& config)
  326. {
  327. // Skip OS X content when not building a Framework or Bundle.
  328. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  329. return;
  330. }
  331. std::string macdir =
  332. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc,
  333. config);
  334. // Get the input file location.
  335. std::string const& input = source.GetFullPath();
  336. // Get the output file location.
  337. std::string output =
  338. cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input));
  339. this->Generator->CleanFiles.insert(
  340. this->Generator->LocalGenerator->MaybeConvertToRelativePath(
  341. this->Generator->LocalGenerator->GetCurrentBinaryDirectory(), output));
  342. output = this->Generator->LocalGenerator->MaybeConvertToRelativePath(
  343. this->Generator->LocalGenerator->GetBinaryDirectory(), output);
  344. // Create a rule to copy the content into the bundle.
  345. std::vector<std::string> depends;
  346. std::vector<std::string> commands;
  347. depends.push_back(input);
  348. std::string copyEcho = cmStrCat("Copying OS X content ", output);
  349. this->Generator->LocalGenerator->AppendEcho(
  350. commands, copyEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  351. std::string copyCommand =
  352. cmStrCat("$(CMAKE_COMMAND) -E copy ",
  353. this->Generator->LocalGenerator->ConvertToOutputFormat(
  354. input, cmOutputConverter::SHELL),
  355. ' ',
  356. this->Generator->LocalGenerator->ConvertToOutputFormat(
  357. output, cmOutputConverter::SHELL));
  358. commands.push_back(std::move(copyCommand));
  359. this->Generator->LocalGenerator->WriteMakeRule(
  360. *this->Generator->BuildFileStream, nullptr, output, depends, commands,
  361. false);
  362. this->Generator->ExtraFiles.insert(output);
  363. }
  364. void cmMakefileTargetGenerator::WriteObjectRuleFiles(
  365. cmSourceFile const& source)
  366. {
  367. // Identify the language of the source file.
  368. const std::string& lang =
  369. this->LocalGenerator->GetSourceFileLanguage(source);
  370. if (lang.empty()) {
  371. // don't know anything about this file so skip it
  372. return;
  373. }
  374. // Get the full path name of the object file.
  375. std::string const& objectName =
  376. this->GeneratorTarget->GetObjectName(&source);
  377. std::string obj =
  378. cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  379. '/', objectName);
  380. // Avoid generating duplicate rules.
  381. if (this->ObjectFiles.find(obj) == this->ObjectFiles.end()) {
  382. this->ObjectFiles.insert(obj);
  383. } else {
  384. std::ostringstream err;
  385. err << "Warning: Source file \"" << source.GetFullPath()
  386. << "\" is listed multiple times for target \""
  387. << this->GeneratorTarget->GetName() << "\".";
  388. cmSystemTools::Message(err.str(), "Warning");
  389. return;
  390. }
  391. // Create the directory containing the object file. This may be a
  392. // subdirectory under the target's directory.
  393. {
  394. std::string dir = cmSystemTools::GetFilenamePath(obj);
  395. cmSystemTools::MakeDirectory(this->LocalGenerator->ConvertToFullPath(dir));
  396. }
  397. // Save this in the target's list of object files.
  398. this->Objects.push_back(obj);
  399. this->CleanFiles.insert(obj);
  400. std::vector<std::string> depends;
  401. // The object file should be checked for dependency integrity.
  402. std::string objFullPath =
  403. cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', obj);
  404. objFullPath = cmSystemTools::CollapseFullPath(objFullPath);
  405. std::string srcFullPath =
  406. cmSystemTools::CollapseFullPath(source.GetFullPath());
  407. this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, lang,
  408. objFullPath, srcFullPath);
  409. this->LocalGenerator->AppendRuleDepend(depends,
  410. this->FlagFileNameFull.c_str());
  411. this->LocalGenerator->AppendRuleDepends(depends,
  412. this->FlagFileDepends[lang]);
  413. // generate the depend scanning rule
  414. this->WriteObjectDependRules(source, depends);
  415. std::string config = this->GetConfigName();
  416. std::string configUpper = cmSystemTools::UpperCase(config);
  417. // Add precompile headers dependencies
  418. const std::string pchSource =
  419. this->GeneratorTarget->GetPchSource(config, lang);
  420. if (!pchSource.empty() && !source.GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  421. std::string const& pchHeader =
  422. this->GeneratorTarget->GetPchHeader(config, lang);
  423. depends.push_back(pchHeader);
  424. if (source.GetFullPath() != pchSource) {
  425. depends.push_back(this->GeneratorTarget->GetPchFile(config, lang));
  426. }
  427. this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, lang,
  428. objFullPath, pchHeader);
  429. }
  430. std::string relativeObj =
  431. cmStrCat(this->LocalGenerator->GetHomeRelativeOutputPath(), obj);
  432. // Write the build rule.
  433. // Build the set of compiler flags.
  434. std::string flags;
  435. // Add language-specific flags.
  436. std::string langFlags = cmStrCat("$(", lang, "_FLAGS)");
  437. this->LocalGenerator->AppendFlags(flags, langFlags);
  438. cmGeneratorExpressionInterpreter genexInterpreter(
  439. this->LocalGenerator, config, this->GeneratorTarget, lang);
  440. // Add Fortran format flags.
  441. if (lang == "Fortran") {
  442. this->AppendFortranFormatFlags(flags, source);
  443. }
  444. // Add flags from source file properties.
  445. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  446. if (const char* cflags = source.GetProperty(COMPILE_FLAGS)) {
  447. const std::string& evaluatedFlags =
  448. genexInterpreter.Evaluate(cflags, COMPILE_FLAGS);
  449. this->LocalGenerator->AppendFlags(flags, evaluatedFlags);
  450. *this->FlagFileStream << "# Custom flags: " << relativeObj
  451. << "_FLAGS = " << evaluatedFlags << "\n"
  452. << "\n";
  453. }
  454. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  455. if (const char* coptions = source.GetProperty(COMPILE_OPTIONS)) {
  456. const std::string& evaluatedOptions =
  457. genexInterpreter.Evaluate(coptions, COMPILE_OPTIONS);
  458. this->LocalGenerator->AppendCompileOptions(flags, evaluatedOptions);
  459. *this->FlagFileStream << "# Custom options: " << relativeObj
  460. << "_OPTIONS = " << evaluatedOptions << "\n"
  461. << "\n";
  462. }
  463. // Add precompile headers compile options.
  464. if (!pchSource.empty() && !source.GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  465. std::string pchOptions;
  466. if (source.GetFullPath() == pchSource) {
  467. pchOptions =
  468. this->GeneratorTarget->GetPchCreateCompileOptions(config, lang);
  469. } else {
  470. pchOptions =
  471. this->GeneratorTarget->GetPchUseCompileOptions(config, lang);
  472. }
  473. const std::string& evaluatedFlags =
  474. genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS);
  475. this->LocalGenerator->AppendCompileOptions(flags, evaluatedFlags);
  476. *this->FlagFileStream << "# PCH options: " << relativeObj
  477. << "_OPTIONS = " << evaluatedFlags << "\n"
  478. << "\n";
  479. }
  480. // Add include directories from source file properties.
  481. std::vector<std::string> includes;
  482. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  483. if (const char* cincludes = source.GetProperty(INCLUDE_DIRECTORIES)) {
  484. const std::string& evaluatedIncludes =
  485. genexInterpreter.Evaluate(cincludes, INCLUDE_DIRECTORIES);
  486. this->LocalGenerator->AppendIncludeDirectories(includes, evaluatedIncludes,
  487. source);
  488. *this->FlagFileStream << "# Custom include directories: " << relativeObj
  489. << "_INCLUDE_DIRECTORIES = " << evaluatedIncludes
  490. << "\n"
  491. << "\n";
  492. }
  493. // Add language-specific defines.
  494. std::set<std::string> defines;
  495. // Add source-specific preprocessor definitions.
  496. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  497. if (const char* compile_defs = source.GetProperty(COMPILE_DEFINITIONS)) {
  498. const std::string& evaluatedDefs =
  499. genexInterpreter.Evaluate(compile_defs, COMPILE_DEFINITIONS);
  500. this->LocalGenerator->AppendDefines(defines, evaluatedDefs);
  501. *this->FlagFileStream << "# Custom defines: " << relativeObj
  502. << "_DEFINES = " << evaluatedDefs << "\n"
  503. << "\n";
  504. }
  505. std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper);
  506. if (const char* config_compile_defs = source.GetProperty(defPropName)) {
  507. const std::string& evaluatedDefs =
  508. genexInterpreter.Evaluate(config_compile_defs, COMPILE_DEFINITIONS);
  509. this->LocalGenerator->AppendDefines(defines, evaluatedDefs);
  510. *this->FlagFileStream << "# Custom defines: " << relativeObj << "_DEFINES_"
  511. << configUpper << " = " << evaluatedDefs << "\n"
  512. << "\n";
  513. }
  514. // Get the output paths for source and object files.
  515. std::string sourceFile = this->LocalGenerator->ConvertToOutputFormat(
  516. source.GetFullPath(), cmOutputConverter::SHELL);
  517. // Construct the build message.
  518. std::vector<std::string> no_commands;
  519. std::vector<std::string> commands;
  520. // add in a progress call if needed
  521. this->NumberOfProgressActions++;
  522. if (!this->NoRuleMessages) {
  523. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  524. this->MakeEchoProgress(progress);
  525. std::string buildEcho =
  526. cmStrCat("Building ", lang, " object ", relativeObj);
  527. this->LocalGenerator->AppendEcho(commands, buildEcho,
  528. cmLocalUnixMakefileGenerator3::EchoBuild,
  529. &progress);
  530. }
  531. std::string targetOutPathReal;
  532. std::string targetOutPathPDB;
  533. std::string targetOutPathCompilePDB;
  534. {
  535. std::string targetFullPathReal;
  536. std::string targetFullPathPDB;
  537. std::string targetFullPathCompilePDB =
  538. this->ComputeTargetCompilePDB(this->GetConfigName());
  539. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  540. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  541. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  542. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  543. targetFullPathReal = this->GeneratorTarget->GetFullPath(
  544. this->GetConfigName(), cmStateEnums::RuntimeBinaryArtifact, true);
  545. targetFullPathPDB = cmStrCat(
  546. this->GeneratorTarget->GetPDBDirectory(this->GetConfigName()), '/',
  547. this->GeneratorTarget->GetPDBName(this->GetConfigName()));
  548. }
  549. targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
  550. this->LocalGenerator->MaybeConvertToRelativePath(
  551. this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
  552. cmOutputConverter::SHELL);
  553. targetOutPathPDB = this->LocalGenerator->ConvertToOutputFormat(
  554. targetFullPathPDB, cmOutputConverter::SHELL);
  555. targetOutPathCompilePDB = this->LocalGenerator->ConvertToOutputFormat(
  556. this->LocalGenerator->MaybeConvertToRelativePath(
  557. this->LocalGenerator->GetCurrentBinaryDirectory(),
  558. targetFullPathCompilePDB),
  559. cmOutputConverter::SHELL);
  560. if (this->LocalGenerator->IsMinGWMake() &&
  561. cmHasLiteralSuffix(targetOutPathCompilePDB, "\\")) {
  562. // mingw32-make incorrectly interprets 'a\ b c' as 'a b' and 'c'
  563. // (but 'a\ b "c"' as 'a\', 'b', and 'c'!). Workaround this by
  564. // avoiding a trailing backslash in the argument.
  565. targetOutPathCompilePDB.back() = '/';
  566. }
  567. }
  568. cmRulePlaceholderExpander::RuleVariables vars;
  569. vars.CMTargetName = this->GeneratorTarget->GetName().c_str();
  570. vars.CMTargetType =
  571. cmState::GetTargetTypeName(this->GeneratorTarget->GetType());
  572. vars.Language = lang.c_str();
  573. vars.Target = targetOutPathReal.c_str();
  574. vars.TargetPDB = targetOutPathPDB.c_str();
  575. vars.TargetCompilePDB = targetOutPathCompilePDB.c_str();
  576. vars.Source = sourceFile.c_str();
  577. std::string shellObj =
  578. this->LocalGenerator->ConvertToOutputFormat(obj, cmOutputConverter::SHELL);
  579. vars.Object = shellObj.c_str();
  580. std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
  581. objectDir = this->LocalGenerator->ConvertToOutputFormat(
  582. this->LocalGenerator->MaybeConvertToRelativePath(
  583. this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
  584. cmOutputConverter::SHELL);
  585. vars.ObjectDir = objectDir.c_str();
  586. std::string objectFileDir = cmSystemTools::GetFilenamePath(obj);
  587. objectFileDir = this->LocalGenerator->ConvertToOutputFormat(
  588. this->LocalGenerator->MaybeConvertToRelativePath(
  589. this->LocalGenerator->GetCurrentBinaryDirectory(), objectFileDir),
  590. cmOutputConverter::SHELL);
  591. vars.ObjectFileDir = objectFileDir.c_str();
  592. vars.Flags = flags.c_str();
  593. std::string definesString = cmStrCat("$(", lang, "_DEFINES)");
  594. this->LocalGenerator->JoinDefines(defines, definesString, lang);
  595. vars.Defines = definesString.c_str();
  596. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  597. includes, this->GeneratorTarget, lang, true, false, config);
  598. this->LocalGenerator->AppendFlags(includesString,
  599. "$(" + lang + "_INCLUDES)");
  600. vars.Includes = includesString.c_str();
  601. // At the moment, it is assumed that C, C++, Fortran, and CUDA have both
  602. // assembly and preprocessor capabilities. The same is true for the
  603. // ability to export compile commands
  604. bool lang_has_preprocessor =
  605. ((lang == "C") || (lang == "CXX") || (lang == "OBJC") ||
  606. (lang == "OBJCXX") || (lang == "Fortran") || (lang == "CUDA"));
  607. bool const lang_has_assembly = lang_has_preprocessor;
  608. bool const lang_can_export_cmds = lang_has_preprocessor;
  609. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  610. this->LocalGenerator->CreateRulePlaceholderExpander());
  611. // Construct the compile rules.
  612. {
  613. std::vector<std::string> compileCommands;
  614. if (lang == "CUDA") {
  615. std::string cmdVar;
  616. if (this->GeneratorTarget->GetPropertyAsBool(
  617. "CUDA_SEPARABLE_COMPILATION")) {
  618. cmdVar = "CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION";
  619. } else if (this->GeneratorTarget->GetPropertyAsBool(
  620. "CUDA_PTX_COMPILATION")) {
  621. cmdVar = "CMAKE_CUDA_COMPILE_PTX_COMPILATION";
  622. } else {
  623. cmdVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION";
  624. }
  625. const std::string& compileRule =
  626. this->Makefile->GetRequiredDefinition(cmdVar);
  627. cmExpandList(compileRule, compileCommands);
  628. } else {
  629. const std::string cmdVar = "CMAKE_" + lang + "_COMPILE_OBJECT";
  630. const std::string& compileRule =
  631. this->Makefile->GetRequiredDefinition(cmdVar);
  632. cmExpandList(compileRule, compileCommands);
  633. }
  634. if (this->Makefile->IsOn("CMAKE_EXPORT_COMPILE_COMMANDS") &&
  635. lang_can_export_cmds && compileCommands.size() == 1) {
  636. std::string compileCommand = compileCommands[0];
  637. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  638. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  639. compileCommand, vars);
  640. std::string workingDirectory = cmSystemTools::CollapseFullPath(
  641. this->LocalGenerator->GetCurrentBinaryDirectory());
  642. compileCommand.replace(compileCommand.find(langFlags), langFlags.size(),
  643. this->GetFlags(lang, this->GetConfigName()));
  644. std::string langDefines = std::string("$(") + lang + "_DEFINES)";
  645. compileCommand.replace(compileCommand.find(langDefines),
  646. langDefines.size(),
  647. this->GetDefines(lang, this->GetConfigName()));
  648. std::string langIncludes = std::string("$(") + lang + "_INCLUDES)";
  649. compileCommand.replace(compileCommand.find(langIncludes),
  650. langIncludes.size(),
  651. this->GetIncludes(lang, this->GetConfigName()));
  652. const char* eliminate[] = {
  653. this->Makefile->GetDefinition("CMAKE_START_TEMP_FILE"),
  654. this->Makefile->GetDefinition("CMAKE_END_TEMP_FILE")
  655. };
  656. for (const char* el : eliminate) {
  657. if (el) {
  658. cmSystemTools::ReplaceString(compileCommand, el, "");
  659. }
  660. }
  661. this->GlobalGenerator->AddCXXCompileCommand(
  662. source.GetFullPath(), workingDirectory, compileCommand);
  663. }
  664. // See if we need to use a compiler launcher like ccache or distcc
  665. std::string compilerLauncher;
  666. if (!compileCommands.empty() &&
  667. (lang == "C" || lang == "CXX" || lang == "Fortran" || lang == "CUDA" ||
  668. lang == "OBJC" || lang == "OBJCXX")) {
  669. std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER";
  670. const char* clauncher =
  671. this->GeneratorTarget->GetProperty(clauncher_prop);
  672. if (clauncher && *clauncher) {
  673. compilerLauncher = clauncher;
  674. }
  675. }
  676. // Maybe insert an include-what-you-use runner.
  677. if (!compileCommands.empty() && (lang == "C" || lang == "CXX")) {
  678. std::string const iwyu_prop = lang + "_INCLUDE_WHAT_YOU_USE";
  679. const char* iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
  680. std::string const tidy_prop = lang + "_CLANG_TIDY";
  681. const char* tidy = this->GeneratorTarget->GetProperty(tidy_prop);
  682. std::string const cpplint_prop = lang + "_CPPLINT";
  683. const char* cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
  684. std::string const cppcheck_prop = lang + "_CPPCHECK";
  685. const char* cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
  686. if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint) ||
  687. (cppcheck && *cppcheck)) {
  688. std::string run_iwyu = "$(CMAKE_COMMAND) -E __run_co_compile";
  689. if (!compilerLauncher.empty()) {
  690. // In __run_co_compile case the launcher command is supplied
  691. // via --launcher=<maybe-list> and consumed
  692. run_iwyu += " --launcher=";
  693. run_iwyu += this->LocalGenerator->EscapeForShell(compilerLauncher);
  694. compilerLauncher.clear();
  695. }
  696. if (iwyu && *iwyu) {
  697. run_iwyu += " --iwyu=";
  698. run_iwyu += this->LocalGenerator->EscapeForShell(iwyu);
  699. }
  700. if (tidy && *tidy) {
  701. run_iwyu += " --tidy=";
  702. const char* driverMode = this->Makefile->GetDefinition(
  703. "CMAKE_" + lang + "_CLANG_TIDY_DRIVER_MODE");
  704. if (!(driverMode && *driverMode)) {
  705. driverMode = lang == "C" ? "gcc" : "g++";
  706. }
  707. run_iwyu += this->LocalGenerator->EscapeForShell(
  708. cmStrCat(tidy, ";--extra-arg-before=--driver-mode=", driverMode));
  709. }
  710. if (cpplint && *cpplint) {
  711. run_iwyu += " --cpplint=";
  712. run_iwyu += this->LocalGenerator->EscapeForShell(cpplint);
  713. }
  714. if (cppcheck && *cppcheck) {
  715. run_iwyu += " --cppcheck=";
  716. run_iwyu += this->LocalGenerator->EscapeForShell(cppcheck);
  717. }
  718. if ((tidy && *tidy) || (cpplint && *cpplint) ||
  719. (cppcheck && *cppcheck)) {
  720. run_iwyu += " --source=";
  721. run_iwyu += sourceFile;
  722. }
  723. run_iwyu += " -- ";
  724. compileCommands.front().insert(0, run_iwyu);
  725. }
  726. }
  727. // If compiler launcher was specified and not consumed above, it
  728. // goes to the beginning of the command line.
  729. if (!compileCommands.empty() && !compilerLauncher.empty()) {
  730. std::vector<std::string> args = cmExpandedList(compilerLauncher, true);
  731. if (!args.empty()) {
  732. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  733. args[0], cmOutputConverter::SHELL);
  734. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  735. i = this->LocalGenerator->EscapeForShell(i);
  736. }
  737. }
  738. compileCommands.front().insert(0, cmJoin(args, " ") + " ");
  739. }
  740. std::string launcher;
  741. {
  742. const char* val = this->LocalGenerator->GetRuleLauncher(
  743. this->GeneratorTarget, "RULE_LAUNCH_COMPILE");
  744. if (val && *val) {
  745. launcher = cmStrCat(val, ' ');
  746. }
  747. }
  748. // Expand placeholders in the commands.
  749. for (std::string& compileCommand : compileCommands) {
  750. compileCommand = cmStrCat(launcher, compileCommand);
  751. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  752. compileCommand, vars);
  753. }
  754. // Change the command working directory to the local build tree.
  755. this->LocalGenerator->CreateCDCommand(
  756. compileCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  757. this->LocalGenerator->GetBinaryDirectory());
  758. cm::append(commands, compileCommands);
  759. }
  760. // Check for extra outputs created by the compilation.
  761. std::vector<std::string> outputs(1, relativeObj);
  762. if (const char* extra_outputs_str = source.GetProperty("OBJECT_OUTPUTS")) {
  763. // Register these as extra files to clean.
  764. cmExpandList(extra_outputs_str, outputs);
  765. this->CleanFiles.insert(outputs.begin() + 1, outputs.end());
  766. }
  767. // Write the rule.
  768. this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
  769. commands);
  770. bool do_preprocess_rules = lang_has_preprocessor &&
  771. this->LocalGenerator->GetCreatePreprocessedSourceRules();
  772. bool do_assembly_rules =
  773. lang_has_assembly && this->LocalGenerator->GetCreateAssemblySourceRules();
  774. if (do_preprocess_rules || do_assembly_rules) {
  775. std::vector<std::string> force_depends;
  776. force_depends.emplace_back("cmake_force");
  777. std::string::size_type dot_pos = relativeObj.rfind('.');
  778. std::string relativeObjBase = relativeObj.substr(0, dot_pos);
  779. dot_pos = obj.rfind('.');
  780. std::string objBase = obj.substr(0, dot_pos);
  781. if (do_preprocess_rules) {
  782. commands.clear();
  783. std::string relativeObjI = relativeObjBase + ".i";
  784. std::string objI = objBase + ".i";
  785. std::string preprocessEcho =
  786. cmStrCat("Preprocessing ", lang, " source to ", objI);
  787. this->LocalGenerator->AppendEcho(
  788. commands, preprocessEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  789. std::string preprocessRuleVar =
  790. cmStrCat("CMAKE_", lang, "_CREATE_PREPROCESSED_SOURCE");
  791. if (const char* preprocessRule =
  792. this->Makefile->GetDefinition(preprocessRuleVar)) {
  793. std::vector<std::string> preprocessCommands =
  794. cmExpandedList(preprocessRule);
  795. std::string shellObjI = this->LocalGenerator->ConvertToOutputFormat(
  796. objI, cmOutputConverter::SHELL);
  797. vars.PreprocessedSource = shellObjI.c_str();
  798. // Expand placeholders in the commands.
  799. for (std::string& preprocessCommand : preprocessCommands) {
  800. // no launcher for preprocessor commands
  801. rulePlaceholderExpander->ExpandRuleVariables(
  802. this->LocalGenerator, preprocessCommand, vars);
  803. }
  804. this->LocalGenerator->CreateCDCommand(
  805. preprocessCommands,
  806. this->LocalGenerator->GetCurrentBinaryDirectory(),
  807. this->LocalGenerator->GetBinaryDirectory());
  808. cm::append(commands, preprocessCommands);
  809. } else {
  810. std::string cmd =
  811. cmStrCat("$(CMAKE_COMMAND) -E cmake_unimplemented_variable ",
  812. preprocessRuleVar);
  813. commands.push_back(std::move(cmd));
  814. }
  815. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  816. relativeObjI, force_depends,
  817. commands, false);
  818. }
  819. if (do_assembly_rules) {
  820. commands.clear();
  821. std::string relativeObjS = relativeObjBase + ".s";
  822. std::string objS = objBase + ".s";
  823. std::string assemblyEcho =
  824. cmStrCat("Compiling ", lang, " source to assembly ", objS);
  825. this->LocalGenerator->AppendEcho(
  826. commands, assemblyEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  827. std::string assemblyRuleVar =
  828. cmStrCat("CMAKE_", lang, "_CREATE_ASSEMBLY_SOURCE");
  829. if (const char* assemblyRule =
  830. this->Makefile->GetDefinition(assemblyRuleVar)) {
  831. std::vector<std::string> assemblyCommands =
  832. cmExpandedList(assemblyRule);
  833. std::string shellObjS = this->LocalGenerator->ConvertToOutputFormat(
  834. objS, cmOutputConverter::SHELL);
  835. vars.AssemblySource = shellObjS.c_str();
  836. // Expand placeholders in the commands.
  837. for (std::string& assemblyCommand : assemblyCommands) {
  838. // no launcher for assembly commands
  839. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  840. assemblyCommand, vars);
  841. }
  842. this->LocalGenerator->CreateCDCommand(
  843. assemblyCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  844. this->LocalGenerator->GetBinaryDirectory());
  845. cm::append(commands, assemblyCommands);
  846. } else {
  847. std::string cmd =
  848. cmStrCat("$(CMAKE_COMMAND) -E cmake_unimplemented_variable ",
  849. assemblyRuleVar);
  850. commands.push_back(std::move(cmd));
  851. }
  852. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  853. relativeObjS, force_depends,
  854. commands, false);
  855. }
  856. }
  857. }
  858. void cmMakefileTargetGenerator::WriteTargetCleanRules()
  859. {
  860. std::vector<std::string> depends;
  861. std::vector<std::string> commands;
  862. // Construct the clean target name.
  863. std::string cleanTarget = cmStrCat(
  864. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget),
  865. "/clean");
  866. // Construct the clean command.
  867. this->LocalGenerator->AppendCleanCommand(commands, this->CleanFiles,
  868. this->GeneratorTarget);
  869. this->LocalGenerator->CreateCDCommand(
  870. commands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  871. this->LocalGenerator->GetBinaryDirectory());
  872. // Write the rule.
  873. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  874. cleanTarget, depends, commands, true);
  875. }
  876. bool cmMakefileTargetGenerator::WriteMakeRule(
  877. std::ostream& os, const char* comment,
  878. const std::vector<std::string>& outputs,
  879. const std::vector<std::string>& depends,
  880. const std::vector<std::string>& commands, bool in_help)
  881. {
  882. bool symbolic = false;
  883. if (outputs.empty()) {
  884. return symbolic;
  885. }
  886. // Check whether we need to bother checking for a symbolic output.
  887. bool need_symbolic = this->GlobalGenerator->GetNeedSymbolicMark();
  888. // Check whether the first output is marked as symbolic.
  889. if (need_symbolic) {
  890. if (cmSourceFile* sf = this->Makefile->GetSource(outputs[0])) {
  891. symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  892. }
  893. }
  894. // We always attach the actual commands to the first output.
  895. this->LocalGenerator->WriteMakeRule(os, comment, outputs[0], depends,
  896. commands, symbolic, in_help);
  897. // For single outputs, we are done.
  898. if (outputs.size() == 1) {
  899. return symbolic;
  900. }
  901. // For multiple outputs, make the extra ones depend on the first one.
  902. std::vector<std::string> const output_depends(1, outputs[0]);
  903. std::string binDir = this->LocalGenerator->GetBinaryDirectory();
  904. for (std::string const& output : cmMakeRange(outputs).advance(1)) {
  905. // Touch the extra output so "make" knows that it was updated,
  906. // but only if the output was actually created.
  907. std::string const out = this->LocalGenerator->ConvertToOutputFormat(
  908. this->LocalGenerator->MaybeConvertToRelativePath(binDir, output),
  909. cmOutputConverter::SHELL);
  910. std::vector<std::string> output_commands;
  911. bool o_symbolic = false;
  912. if (need_symbolic) {
  913. if (cmSourceFile* sf = this->Makefile->GetSource(output)) {
  914. o_symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  915. }
  916. }
  917. symbolic = symbolic && o_symbolic;
  918. if (!o_symbolic) {
  919. output_commands.push_back("@$(CMAKE_COMMAND) -E touch_nocreate " + out);
  920. }
  921. this->LocalGenerator->WriteMakeRule(os, nullptr, output, output_depends,
  922. output_commands, o_symbolic, in_help);
  923. if (!o_symbolic) {
  924. // At build time, remove the first output if this one does not exist
  925. // so that "make" will rerun the real commands that create this one.
  926. MultipleOutputPairsType::value_type p(output, outputs[0]);
  927. this->MultipleOutputPairs.insert(p);
  928. }
  929. }
  930. return symbolic;
  931. }
  932. void cmMakefileTargetGenerator::WriteTargetDependRules()
  933. {
  934. // must write the targets depend info file
  935. std::string dir =
  936. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  937. this->InfoFileNameFull = cmStrCat(dir, "/DependInfo.cmake");
  938. this->InfoFileNameFull =
  939. this->LocalGenerator->ConvertToFullPath(this->InfoFileNameFull);
  940. this->InfoFileStream =
  941. cm::make_unique<cmGeneratedFileStream>(this->InfoFileNameFull);
  942. if (!this->InfoFileStream) {
  943. return;
  944. }
  945. this->InfoFileStream->SetCopyIfDifferent(true);
  946. this->LocalGenerator->WriteDependLanguageInfo(*this->InfoFileStream,
  947. this->GeneratorTarget);
  948. // Store multiple output pairs in the depend info file.
  949. if (!this->MultipleOutputPairs.empty()) {
  950. /* clang-format off */
  951. *this->InfoFileStream
  952. << "\n"
  953. << "# Pairs of files generated by the same build rule.\n"
  954. << "set(CMAKE_MULTIPLE_OUTPUT_PAIRS\n";
  955. /* clang-format on */
  956. for (auto const& pi : this->MultipleOutputPairs) {
  957. *this->InfoFileStream
  958. << " " << cmOutputConverter::EscapeForCMake(pi.first) << " "
  959. << cmOutputConverter::EscapeForCMake(pi.second) << "\n";
  960. }
  961. *this->InfoFileStream << " )\n\n";
  962. }
  963. // Store list of targets linked directly or transitively.
  964. {
  965. /* clang-format off */
  966. *this->InfoFileStream
  967. << "\n"
  968. << "# Targets to which this target links.\n"
  969. << "set(CMAKE_TARGET_LINKED_INFO_FILES\n";
  970. /* clang-format on */
  971. std::vector<std::string> dirs =
  972. this->GetLinkedTargetDirectories(this->GetConfigName());
  973. for (std::string const& d : dirs) {
  974. *this->InfoFileStream << " \"" << d << "/DependInfo.cmake\"\n";
  975. }
  976. *this->InfoFileStream << " )\n";
  977. }
  978. std::string const& working_dir =
  979. this->LocalGenerator->GetCurrentBinaryDirectory();
  980. /* clang-format off */
  981. *this->InfoFileStream
  982. << "\n"
  983. << "# Fortran module output directory.\n"
  984. << "set(CMAKE_Fortran_TARGET_MODULE_DIR \""
  985. << this->GeneratorTarget->GetFortranModuleDirectory(working_dir)
  986. << "\")\n";
  987. /* clang-format on */
  988. // and now write the rule to use it
  989. std::vector<std::string> depends;
  990. std::vector<std::string> commands;
  991. // Construct the name of the dependency generation target.
  992. std::string depTarget = cmStrCat(
  993. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget),
  994. "/depend");
  995. // Add a command to call CMake to scan dependencies. CMake will
  996. // touch the corresponding depends file after scanning dependencies.
  997. std::ostringstream depCmd;
  998. // TODO: Account for source file properties and directory-level
  999. // definitions when scanning for dependencies.
  1000. #if !defined(_WIN32) || defined(__CYGWIN__)
  1001. // This platform supports symlinks, so cmSystemTools will translate
  1002. // paths. Make sure PWD is set to the original name of the home
  1003. // output directory to help cmSystemTools to create the same
  1004. // translation table for the dependency scanning process.
  1005. depCmd << "cd "
  1006. << (this->LocalGenerator->ConvertToOutputFormat(
  1007. cmSystemTools::CollapseFullPath(
  1008. this->LocalGenerator->GetBinaryDirectory()),
  1009. cmOutputConverter::SHELL))
  1010. << " && ";
  1011. #endif
  1012. // Generate a call this signature:
  1013. //
  1014. // cmake -E cmake_depends <generator>
  1015. // <home-src-dir> <start-src-dir>
  1016. // <home-out-dir> <start-out-dir>
  1017. // <dep-info> --color=$(COLOR)
  1018. //
  1019. // This gives the dependency scanner enough information to recreate
  1020. // the state of our local generator sufficiently for its needs.
  1021. depCmd << "$(CMAKE_COMMAND) -E cmake_depends \""
  1022. << this->GlobalGenerator->GetName() << "\" "
  1023. << this->LocalGenerator->ConvertToOutputFormat(
  1024. cmSystemTools::CollapseFullPath(
  1025. this->LocalGenerator->GetSourceDirectory()),
  1026. cmOutputConverter::SHELL)
  1027. << " "
  1028. << this->LocalGenerator->ConvertToOutputFormat(
  1029. cmSystemTools::CollapseFullPath(
  1030. this->LocalGenerator->GetCurrentSourceDirectory()),
  1031. cmOutputConverter::SHELL)
  1032. << " "
  1033. << this->LocalGenerator->ConvertToOutputFormat(
  1034. cmSystemTools::CollapseFullPath(
  1035. this->LocalGenerator->GetBinaryDirectory()),
  1036. cmOutputConverter::SHELL)
  1037. << " "
  1038. << this->LocalGenerator->ConvertToOutputFormat(
  1039. cmSystemTools::CollapseFullPath(
  1040. this->LocalGenerator->GetCurrentBinaryDirectory()),
  1041. cmOutputConverter::SHELL)
  1042. << " "
  1043. << this->LocalGenerator->ConvertToOutputFormat(
  1044. cmSystemTools::CollapseFullPath(this->InfoFileNameFull),
  1045. cmOutputConverter::SHELL);
  1046. if (this->LocalGenerator->GetColorMakefile()) {
  1047. depCmd << " --color=$(COLOR)";
  1048. }
  1049. commands.push_back(depCmd.str());
  1050. // Make sure all custom command outputs in this target are built.
  1051. if (this->CustomCommandDriver == OnDepends) {
  1052. this->DriveCustomCommands(depends);
  1053. }
  1054. // Write the rule.
  1055. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1056. depTarget, depends, commands, true);
  1057. }
  1058. void cmMakefileTargetGenerator::DriveCustomCommands(
  1059. std::vector<std::string>& depends)
  1060. {
  1061. // Depend on all custom command outputs.
  1062. std::vector<cmSourceFile*> sources;
  1063. this->GeneratorTarget->GetSourceFiles(
  1064. sources, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  1065. for (cmSourceFile* source : sources) {
  1066. if (cmCustomCommand* cc = source->GetCustomCommand()) {
  1067. cmCustomCommandGenerator ccg(*cc, this->GetConfigName(),
  1068. this->LocalGenerator);
  1069. cm::append(depends, ccg.GetOutputs());
  1070. }
  1071. }
  1072. }
  1073. void cmMakefileTargetGenerator::WriteObjectDependRules(
  1074. cmSourceFile const& source, std::vector<std::string>& depends)
  1075. {
  1076. // Create the list of dependencies known at cmake time. These are
  1077. // shared between the object file and dependency scanning rule.
  1078. depends.push_back(source.GetFullPath());
  1079. if (const char* objectDeps = source.GetProperty("OBJECT_DEPENDS")) {
  1080. cmExpandList(objectDeps, depends);
  1081. }
  1082. }
  1083. void cmMakefileTargetGenerator::GenerateCustomRuleFile(
  1084. cmCustomCommandGenerator const& ccg)
  1085. {
  1086. // Collect the commands.
  1087. std::vector<std::string> commands;
  1088. std::string comment = this->LocalGenerator->ConstructComment(ccg);
  1089. if (!comment.empty()) {
  1090. // add in a progress call if needed
  1091. this->NumberOfProgressActions++;
  1092. if (!this->NoRuleMessages) {
  1093. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  1094. this->MakeEchoProgress(progress);
  1095. this->LocalGenerator->AppendEcho(
  1096. commands, comment, cmLocalUnixMakefileGenerator3::EchoGenerate,
  1097. &progress);
  1098. }
  1099. }
  1100. // Now append the actual user-specified commands.
  1101. std::ostringstream content;
  1102. this->LocalGenerator->AppendCustomCommand(
  1103. commands, ccg, this->GeneratorTarget,
  1104. this->LocalGenerator->GetBinaryDirectory(), false, &content);
  1105. // Collect the dependencies.
  1106. std::vector<std::string> depends;
  1107. this->LocalGenerator->AppendCustomDepend(depends, ccg);
  1108. // Write the rule.
  1109. const std::vector<std::string>& outputs = ccg.GetOutputs();
  1110. bool symbolic = this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs,
  1111. depends, commands);
  1112. // If the rule has changed make sure the output is rebuilt.
  1113. if (!symbolic) {
  1114. this->GlobalGenerator->AddRuleHash(ccg.GetOutputs(), content.str());
  1115. }
  1116. // Setup implicit dependency scanning.
  1117. for (auto const& idi : ccg.GetCC().GetImplicitDepends()) {
  1118. std::string objFullPath = cmSystemTools::CollapseFullPath(outputs[0]);
  1119. std::string srcFullPath = cmSystemTools::CollapseFullPath(idi.second);
  1120. this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, idi.first,
  1121. objFullPath, srcFullPath);
  1122. }
  1123. }
  1124. void cmMakefileTargetGenerator::MakeEchoProgress(
  1125. cmLocalUnixMakefileGenerator3::EchoProgress& progress) const
  1126. {
  1127. progress.Dir =
  1128. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), "/CMakeFiles");
  1129. std::ostringstream progressArg;
  1130. progressArg << "$(CMAKE_PROGRESS_" << this->NumberOfProgressActions << ")";
  1131. progress.Arg = progressArg.str();
  1132. }
  1133. void cmMakefileTargetGenerator::WriteObjectsVariable(
  1134. std::string& variableName, std::string& variableNameExternal,
  1135. bool useWatcomQuote)
  1136. {
  1137. // Write a make variable assignment that lists all objects for the
  1138. // target.
  1139. variableName = this->LocalGenerator->CreateMakeVariable(
  1140. this->GeneratorTarget->GetName(), "_OBJECTS");
  1141. *this->BuildFileStream << "# Object files for target "
  1142. << this->GeneratorTarget->GetName() << "\n"
  1143. << variableName << " =";
  1144. std::string object;
  1145. const char* lineContinue =
  1146. this->Makefile->GetDefinition("CMAKE_MAKE_LINE_CONTINUE");
  1147. if (!lineContinue) {
  1148. lineContinue = "\\";
  1149. }
  1150. const char* pchExtension =
  1151. this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  1152. for (std::string const& obj : this->Objects) {
  1153. if (cmSystemTools::StringEndsWith(obj, pchExtension)) {
  1154. continue;
  1155. }
  1156. *this->BuildFileStream << " " << lineContinue << "\n";
  1157. *this->BuildFileStream
  1158. << cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1159. obj, useWatcomQuote);
  1160. }
  1161. *this->BuildFileStream << "\n";
  1162. // Write a make variable assignment that lists all external objects
  1163. // for the target.
  1164. variableNameExternal = this->LocalGenerator->CreateMakeVariable(
  1165. this->GeneratorTarget->GetName(), "_EXTERNAL_OBJECTS");
  1166. /* clang-format off */
  1167. *this->BuildFileStream
  1168. << "\n"
  1169. << "# External object files for target "
  1170. << this->GeneratorTarget->GetName() << "\n"
  1171. << variableNameExternal << " =";
  1172. /* clang-format on */
  1173. std::string currentBinDir =
  1174. this->LocalGenerator->GetCurrentBinaryDirectory();
  1175. for (std::string const& obj : this->ExternalObjects) {
  1176. object =
  1177. this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, obj);
  1178. *this->BuildFileStream << " " << lineContinue << "\n";
  1179. *this->BuildFileStream
  1180. << cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1181. obj, useWatcomQuote);
  1182. }
  1183. *this->BuildFileStream << "\n"
  1184. << "\n";
  1185. }
  1186. class cmMakefileTargetGeneratorObjectStrings
  1187. {
  1188. public:
  1189. cmMakefileTargetGeneratorObjectStrings(std::vector<std::string>& strings,
  1190. cmOutputConverter* outputConverter,
  1191. cmStateDirectory const& stateDir,
  1192. std::string::size_type limit)
  1193. : Strings(strings)
  1194. , OutputConverter(outputConverter)
  1195. , StateDir(stateDir)
  1196. , LengthLimit(limit)
  1197. {
  1198. this->Space = "";
  1199. }
  1200. void Feed(std::string const& obj)
  1201. {
  1202. // Construct the name of the next object.
  1203. this->NextObject = this->OutputConverter->ConvertToOutputFormat(
  1204. this->MaybeConvertToRelativePath(obj), cmOutputConverter::RESPONSE);
  1205. // Roll over to next string if the limit will be exceeded.
  1206. if (this->LengthLimit != std::string::npos &&
  1207. (this->CurrentString.length() + 1 + this->NextObject.length() >
  1208. this->LengthLimit)) {
  1209. this->Strings.push_back(this->CurrentString);
  1210. this->CurrentString.clear();
  1211. this->Space = "";
  1212. }
  1213. // Separate from previous object.
  1214. this->CurrentString += this->Space;
  1215. this->Space = " ";
  1216. // Append this object.
  1217. this->CurrentString += this->NextObject;
  1218. }
  1219. void Done() { this->Strings.push_back(this->CurrentString); }
  1220. private:
  1221. std::string MaybeConvertToRelativePath(std::string const& obj)
  1222. {
  1223. if (!this->StateDir.ContainsBoth(this->StateDir.GetCurrentBinary(), obj)) {
  1224. return obj;
  1225. }
  1226. return cmSystemTools::ForceToRelativePath(
  1227. this->StateDir.GetCurrentBinary(), obj);
  1228. }
  1229. std::vector<std::string>& Strings;
  1230. cmOutputConverter* OutputConverter;
  1231. cmStateDirectory StateDir;
  1232. std::string::size_type LengthLimit;
  1233. std::string CurrentString;
  1234. std::string NextObject;
  1235. const char* Space;
  1236. };
  1237. void cmMakefileTargetGenerator::WriteObjectsStrings(
  1238. std::vector<std::string>& objStrings, std::string::size_type limit)
  1239. {
  1240. const char* pchExtension =
  1241. this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  1242. cmMakefileTargetGeneratorObjectStrings helper(
  1243. objStrings, this->LocalGenerator,
  1244. this->LocalGenerator->GetStateSnapshot().GetDirectory(), limit);
  1245. for (std::string const& obj : this->Objects) {
  1246. if (cmSystemTools::StringEndsWith(obj, pchExtension)) {
  1247. continue;
  1248. }
  1249. helper.Feed(obj);
  1250. }
  1251. for (std::string const& obj : this->ExternalObjects) {
  1252. helper.Feed(obj);
  1253. }
  1254. helper.Done();
  1255. }
  1256. void cmMakefileTargetGenerator::WriteTargetDriverRule(
  1257. const std::string& main_output, bool relink)
  1258. {
  1259. // Compute the name of the driver target.
  1260. std::string dir =
  1261. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget);
  1262. std::string buildTargetRuleName =
  1263. cmStrCat(dir, relink ? "/preinstall" : "/build");
  1264. buildTargetRuleName = this->LocalGenerator->MaybeConvertToRelativePath(
  1265. this->LocalGenerator->GetBinaryDirectory(), buildTargetRuleName);
  1266. // Build the list of target outputs to drive.
  1267. std::vector<std::string> depends;
  1268. depends.push_back(main_output);
  1269. const char* comment = nullptr;
  1270. if (relink) {
  1271. // Setup the comment for the preinstall driver.
  1272. comment = "Rule to relink during preinstall.";
  1273. } else {
  1274. // Setup the comment for the main build driver.
  1275. comment = "Rule to build all files generated by this target.";
  1276. // Make sure all custom command outputs in this target are built.
  1277. if (this->CustomCommandDriver == OnBuild) {
  1278. this->DriveCustomCommands(depends);
  1279. }
  1280. // Make sure the extra files are built.
  1281. cm::append(depends, this->ExtraFiles);
  1282. }
  1283. // Write the driver rule.
  1284. std::vector<std::string> no_commands;
  1285. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, comment,
  1286. buildTargetRuleName, depends,
  1287. no_commands, true);
  1288. }
  1289. void cmMakefileTargetGenerator::AppendTargetDepends(
  1290. std::vector<std::string>& depends)
  1291. {
  1292. // Static libraries never depend on anything for linking.
  1293. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  1294. return;
  1295. }
  1296. // Loop over all library dependencies.
  1297. const std::string& cfg = this->GetConfigName();
  1298. if (cmComputeLinkInformation* cli =
  1299. this->GeneratorTarget->GetLinkInformation(cfg)) {
  1300. cm::append(depends, cli->GetDepends());
  1301. }
  1302. }
  1303. void cmMakefileTargetGenerator::AppendObjectDepends(
  1304. std::vector<std::string>& depends)
  1305. {
  1306. // Add dependencies on the compiled object files.
  1307. std::string const& relPath =
  1308. this->LocalGenerator->GetHomeRelativeOutputPath();
  1309. for (std::string const& obj : this->Objects) {
  1310. std::string objTarget = cmStrCat(relPath, obj);
  1311. depends.push_back(std::move(objTarget));
  1312. }
  1313. // Add dependencies on the external object files.
  1314. cm::append(depends, this->ExternalObjects);
  1315. // Add a dependency on the rule file itself.
  1316. this->LocalGenerator->AppendRuleDepend(depends,
  1317. this->BuildFileNameFull.c_str());
  1318. }
  1319. void cmMakefileTargetGenerator::AppendLinkDepends(
  1320. std::vector<std::string>& depends, const std::string& linkLanguage)
  1321. {
  1322. this->AppendObjectDepends(depends);
  1323. // Add dependencies on targets that must be built first.
  1324. this->AppendTargetDepends(depends);
  1325. // Add a dependency on the link definitions file, if any.
  1326. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1327. this->GeneratorTarget->GetModuleDefinitionInfo(
  1328. this->GetConfigName())) {
  1329. for (cmSourceFile const* src : mdi->Sources) {
  1330. depends.push_back(src->GetFullPath());
  1331. }
  1332. }
  1333. // Add a dependency on user-specified manifest files, if any.
  1334. std::vector<cmSourceFile const*> manifest_srcs;
  1335. this->GeneratorTarget->GetManifests(manifest_srcs, this->GetConfigName());
  1336. for (cmSourceFile const* manifest_src : manifest_srcs) {
  1337. depends.push_back(manifest_src->GetFullPath());
  1338. }
  1339. // Add user-specified dependencies.
  1340. this->GeneratorTarget->GetLinkDepends(depends, this->GetConfigName(),
  1341. linkLanguage);
  1342. }
  1343. std::string cmMakefileTargetGenerator::GetLinkRule(
  1344. const std::string& linkRuleVar)
  1345. {
  1346. std::string linkRule = this->Makefile->GetRequiredDefinition(linkRuleVar);
  1347. if (this->GeneratorTarget->HasImplibGNUtoMS(this->GetConfigName())) {
  1348. std::string ruleVar =
  1349. cmStrCat("CMAKE_",
  1350. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName()),
  1351. "_GNUtoMS_RULE");
  1352. if (const char* rule = this->Makefile->GetDefinition(ruleVar)) {
  1353. linkRule += rule;
  1354. }
  1355. }
  1356. return linkRule;
  1357. }
  1358. void cmMakefileTargetGenerator::CloseFileStreams()
  1359. {
  1360. this->BuildFileStream.reset();
  1361. this->InfoFileStream.reset();
  1362. this->FlagFileStream.reset();
  1363. }
  1364. void cmMakefileTargetGenerator::CreateLinkScript(
  1365. const char* name, std::vector<std::string> const& link_commands,
  1366. std::vector<std::string>& makefile_commands,
  1367. std::vector<std::string>& makefile_depends)
  1368. {
  1369. // Create the link script file.
  1370. std::string linkScriptName =
  1371. cmStrCat(this->TargetBuildDirectoryFull, '/', name);
  1372. cmGeneratedFileStream linkScriptStream(linkScriptName);
  1373. linkScriptStream.SetCopyIfDifferent(true);
  1374. for (std::string const& link_command : link_commands) {
  1375. // Do not write out empty commands or commands beginning in the
  1376. // shell no-op ":".
  1377. if (!link_command.empty() && link_command[0] != ':') {
  1378. linkScriptStream << link_command << "\n";
  1379. }
  1380. }
  1381. // Create the makefile command to invoke the link script.
  1382. std::string link_command = cmStrCat(
  1383. "$(CMAKE_COMMAND) -E cmake_link_script ",
  1384. this->LocalGenerator->ConvertToOutputFormat(
  1385. this->LocalGenerator->MaybeConvertToRelativePath(
  1386. this->LocalGenerator->GetCurrentBinaryDirectory(), linkScriptName),
  1387. cmOutputConverter::SHELL),
  1388. " --verbose=$(VERBOSE)");
  1389. makefile_commands.push_back(std::move(link_command));
  1390. makefile_depends.push_back(std::move(linkScriptName));
  1391. }
  1392. bool cmMakefileTargetGenerator::CheckUseResponseFileForObjects(
  1393. std::string const& l) const
  1394. {
  1395. // Check for an explicit setting one way or the other.
  1396. std::string const responseVar =
  1397. "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_OBJECTS";
  1398. if (const char* val = this->Makefile->GetDefinition(responseVar)) {
  1399. if (*val) {
  1400. return cmIsOn(val);
  1401. }
  1402. }
  1403. // Check for a system limit.
  1404. if (size_t const limit = cmSystemTools::CalculateCommandLineLengthLimit()) {
  1405. // Compute the total length of our list of object files with room
  1406. // for argument separation and quoting. This does not convert paths
  1407. // relative to CMAKE_CURRENT_BINARY_DIR like the final list will be, so the
  1408. // actual list will likely be much shorter than this. However, in the
  1409. // worst case all objects will remain as absolute paths.
  1410. size_t length = 0;
  1411. for (std::string const& obj : this->Objects) {
  1412. length += obj.size() + 3;
  1413. }
  1414. for (std::string const& ext_obj : this->ExternalObjects) {
  1415. length += ext_obj.size() + 3;
  1416. }
  1417. // We need to guarantee room for both objects and libraries, so
  1418. // if the objects take up more than half then use a response file
  1419. // for them.
  1420. if (length > (limit / 2)) {
  1421. return true;
  1422. }
  1423. }
  1424. // We do not need a response file for objects.
  1425. return false;
  1426. }
  1427. bool cmMakefileTargetGenerator::CheckUseResponseFileForLibraries(
  1428. std::string const& l) const
  1429. {
  1430. // Check for an explicit setting one way or the other.
  1431. std::string const responseVar =
  1432. "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_LIBRARIES";
  1433. if (const char* val = this->Makefile->GetDefinition(responseVar)) {
  1434. if (*val) {
  1435. return cmIsOn(val);
  1436. }
  1437. }
  1438. // We do not need a response file for libraries.
  1439. return false;
  1440. }
  1441. std::string cmMakefileTargetGenerator::CreateResponseFile(
  1442. const char* name, std::string const& options,
  1443. std::vector<std::string>& makefile_depends)
  1444. {
  1445. // Create the response file.
  1446. std::string responseFileNameFull =
  1447. cmStrCat(this->TargetBuildDirectoryFull, '/', name);
  1448. cmGeneratedFileStream responseStream(responseFileNameFull);
  1449. responseStream.SetCopyIfDifferent(true);
  1450. responseStream << options << "\n";
  1451. // Add a dependency so the target will rebuild when the set of
  1452. // objects changes.
  1453. makefile_depends.push_back(std::move(responseFileNameFull));
  1454. // Construct the name to be used on the command line.
  1455. std::string responseFileName =
  1456. cmStrCat(this->TargetBuildDirectory, '/', name);
  1457. return responseFileName;
  1458. }
  1459. std::unique_ptr<cmLinkLineComputer>
  1460. cmMakefileTargetGenerator::CreateLinkLineComputer(
  1461. cmOutputConverter* outputConverter, cmStateDirectory const& stateDir)
  1462. {
  1463. if (this->Makefile->IsOn("MSVC60")) {
  1464. return this->GlobalGenerator->CreateMSVC60LinkLineComputer(outputConverter,
  1465. stateDir);
  1466. }
  1467. return this->GlobalGenerator->CreateLinkLineComputer(outputConverter,
  1468. stateDir);
  1469. }
  1470. void cmMakefileTargetGenerator::CreateLinkLibs(
  1471. cmLinkLineComputer* linkLineComputer, std::string& linkLibs,
  1472. bool useResponseFile, std::vector<std::string>& makefile_depends)
  1473. {
  1474. std::string frameworkPath;
  1475. std::string linkPath;
  1476. cmComputeLinkInformation* pcli =
  1477. this->GeneratorTarget->GetLinkInformation(this->GetConfigName());
  1478. this->LocalGenerator->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1479. frameworkPath, linkPath);
  1480. linkLibs = frameworkPath + linkPath + linkLibs;
  1481. if (useResponseFile &&
  1482. linkLibs.find_first_not_of(' ') != std::string::npos) {
  1483. // Lookup the response file reference flag.
  1484. std::string responseFlagVar =
  1485. cmStrCat("CMAKE_",
  1486. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName()),
  1487. "_RESPONSE_FILE_LINK_FLAG");
  1488. const char* responseFlag = this->Makefile->GetDefinition(responseFlagVar);
  1489. if (!responseFlag) {
  1490. responseFlag = "@";
  1491. }
  1492. // Create this response file.
  1493. std::string link_rsp =
  1494. this->CreateResponseFile("linklibs.rsp", linkLibs, makefile_depends);
  1495. // Reference the response file.
  1496. linkLibs = cmStrCat(responseFlag,
  1497. this->LocalGenerator->ConvertToOutputFormat(
  1498. link_rsp, cmOutputConverter::SHELL));
  1499. }
  1500. }
  1501. void cmMakefileTargetGenerator::CreateObjectLists(
  1502. bool useLinkScript, bool useArchiveRules, bool useResponseFile,
  1503. std::string& buildObjs, std::vector<std::string>& makefile_depends,
  1504. bool useWatcomQuote)
  1505. {
  1506. std::string variableName;
  1507. std::string variableNameExternal;
  1508. this->WriteObjectsVariable(variableName, variableNameExternal,
  1509. useWatcomQuote);
  1510. if (useResponseFile) {
  1511. // MSVC response files cannot exceed 128K.
  1512. std::string::size_type const responseFileLimit = 131000;
  1513. // Construct the individual object list strings.
  1514. std::vector<std::string> object_strings;
  1515. this->WriteObjectsStrings(object_strings, responseFileLimit);
  1516. // Lookup the response file reference flag.
  1517. std::string responseFlagVar =
  1518. cmStrCat("CMAKE_",
  1519. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName()),
  1520. "_RESPONSE_FILE_LINK_FLAG");
  1521. const char* responseFlag = this->Makefile->GetDefinition(responseFlagVar);
  1522. if (!responseFlag) {
  1523. responseFlag = "@";
  1524. }
  1525. // Write a response file for each string.
  1526. const char* sep = "";
  1527. for (unsigned int i = 0; i < object_strings.size(); ++i) {
  1528. // Number the response files.
  1529. char rsp[32];
  1530. sprintf(rsp, "objects%u.rsp", i + 1);
  1531. // Create this response file.
  1532. std::string objects_rsp =
  1533. this->CreateResponseFile(rsp, object_strings[i], makefile_depends);
  1534. // Separate from previous response file references.
  1535. buildObjs += sep;
  1536. sep = " ";
  1537. // Reference the response file.
  1538. buildObjs += responseFlag;
  1539. buildObjs += this->LocalGenerator->ConvertToOutputFormat(
  1540. objects_rsp, cmOutputConverter::SHELL);
  1541. }
  1542. } else if (useLinkScript) {
  1543. if (!useArchiveRules) {
  1544. std::vector<std::string> objStrings;
  1545. this->WriteObjectsStrings(objStrings);
  1546. buildObjs = objStrings[0];
  1547. }
  1548. } else {
  1549. buildObjs =
  1550. cmStrCat("$(", variableName, ") $(", variableNameExternal, ')');
  1551. }
  1552. }
  1553. void cmMakefileTargetGenerator::AddIncludeFlags(std::string& flags,
  1554. const std::string& lang,
  1555. const std::string& /*config*/)
  1556. {
  1557. std::string responseVar =
  1558. cmStrCat("CMAKE_", lang, "_USE_RESPONSE_FILE_FOR_INCLUDES");
  1559. bool useResponseFile = this->Makefile->IsOn(responseVar);
  1560. std::vector<std::string> includes;
  1561. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1562. lang, this->GetConfigName());
  1563. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  1564. includes, this->GeneratorTarget, lang, false, useResponseFile,
  1565. this->GetConfigName());
  1566. if (includeFlags.empty()) {
  1567. return;
  1568. }
  1569. if (useResponseFile) {
  1570. std::string const responseFlagVar =
  1571. "CMAKE_" + lang + "_RESPONSE_FILE_FLAG";
  1572. std::string responseFlag =
  1573. this->Makefile->GetSafeDefinition(responseFlagVar);
  1574. if (responseFlag.empty()) {
  1575. responseFlag = "@";
  1576. }
  1577. std::string name = cmStrCat("includes_", lang, ".rsp");
  1578. std::string arg = std::move(responseFlag) +
  1579. this->CreateResponseFile(name.c_str(), includeFlags,
  1580. this->FlagFileDepends[lang]);
  1581. this->LocalGenerator->AppendFlags(flags, arg);
  1582. } else {
  1583. this->LocalGenerator->AppendFlags(flags, includeFlags);
  1584. }
  1585. }
  1586. void cmMakefileTargetGenerator::GenDefFile(
  1587. std::vector<std::string>& real_link_commands)
  1588. {
  1589. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1590. this->GeneratorTarget->GetModuleDefinitionInfo(this->GetConfigName());
  1591. if (!mdi || !mdi->DefFileGenerated) {
  1592. return;
  1593. }
  1594. std::string cmd = cmSystemTools::GetCMakeCommand();
  1595. cmd = cmStrCat(
  1596. this->LocalGenerator->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL),
  1597. " -E __create_def ",
  1598. this->LocalGenerator->ConvertToOutputFormat(
  1599. this->LocalGenerator->MaybeConvertToRelativePath(
  1600. this->LocalGenerator->GetCurrentBinaryDirectory(), mdi->DefFile),
  1601. cmOutputConverter::SHELL),
  1602. ' ');
  1603. std::string objlist_file = mdi->DefFile + ".objs";
  1604. cmd += this->LocalGenerator->ConvertToOutputFormat(
  1605. this->LocalGenerator->MaybeConvertToRelativePath(
  1606. this->LocalGenerator->GetCurrentBinaryDirectory(), objlist_file),
  1607. cmOutputConverter::SHELL);
  1608. const char* nm_executable = this->Makefile->GetDefinition("CMAKE_NM");
  1609. if (nm_executable && *nm_executable) {
  1610. cmd += " --nm=";
  1611. cmd += this->LocalCommonGenerator->ConvertToOutputFormat(
  1612. nm_executable, cmOutputConverter::SHELL);
  1613. }
  1614. real_link_commands.insert(real_link_commands.begin(), cmd);
  1615. // create a list of obj files for the -E __create_def to read
  1616. cmGeneratedFileStream fout(objlist_file);
  1617. if (mdi->WindowsExportAllSymbols) {
  1618. for (std::string const& obj : this->Objects) {
  1619. if (cmHasLiteralSuffix(obj, ".obj")) {
  1620. fout << obj << "\n";
  1621. }
  1622. }
  1623. for (std::string const& obj : this->ExternalObjects) {
  1624. fout << obj << "\n";
  1625. }
  1626. }
  1627. for (cmSourceFile const* src : mdi->Sources) {
  1628. fout << src->GetFullPath() << "\n";
  1629. }
  1630. }