cmMakefileTargetGenerator.cxx 71 KB

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