cmMakefileTargetGenerator.cxx 70 KB

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