cmMakefileTargetGenerator.cxx 70 KB

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