cmMakefileTargetGenerator.cxx 69 KB

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