cmMakefileTargetGenerator.cxx 72 KB

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