cmMakefileTargetGenerator.cxx 71 KB

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