cmMakefileTargetGenerator.cxx 67 KB

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