cmMakefileTargetGenerator.cxx 69 KB

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