cmMakefileTargetGenerator.cxx 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769
  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().c_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(
  394. this->GeneratorTarget, lang, objFullPath.c_str(), srcFullPath.c_str());
  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 = std::string("CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION");
  586. } else if (this->GeneratorTarget->GetPropertyAsBool(
  587. "CUDA_PTX_COMPILATION")) {
  588. cmdVar = std::string("CMAKE_CUDA_COMPILE_PTX_COMPILATION");
  589. } else {
  590. cmdVar = std::string("CMAKE_CUDA_COMPILE_WHOLE_COMPILATION");
  591. }
  592. std::string compileRule = this->Makefile->GetRequiredDefinition(cmdVar);
  593. cmSystemTools::ExpandListArgument(compileRule, compileCommands);
  594. } else {
  595. const std::string cmdVar =
  596. std::string("CMAKE_") + lang + "_COMPILE_OBJECT";
  597. std::string compileRule = this->Makefile->GetRequiredDefinition(cmdVar);
  598. cmSystemTools::ExpandListArgument(compileRule, compileCommands);
  599. }
  600. if (this->Makefile->IsOn("CMAKE_EXPORT_COMPILE_COMMANDS") &&
  601. lang_can_export_cmds && compileCommands.size() == 1) {
  602. std::string compileCommand = compileCommands[0];
  603. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  604. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  605. compileCommand, vars);
  606. std::string workingDirectory = cmSystemTools::CollapseFullPath(
  607. this->LocalGenerator->GetCurrentBinaryDirectory());
  608. compileCommand.replace(compileCommand.find(langFlags), langFlags.size(),
  609. this->GetFlags(lang));
  610. std::string langDefines = std::string("$(") + lang + "_DEFINES)";
  611. compileCommand.replace(compileCommand.find(langDefines),
  612. langDefines.size(), this->GetDefines(lang));
  613. std::string langIncludes = std::string("$(") + lang + "_INCLUDES)";
  614. compileCommand.replace(compileCommand.find(langIncludes),
  615. langIncludes.size(), this->GetIncludes(lang));
  616. this->GlobalGenerator->AddCXXCompileCommand(
  617. source.GetFullPath(), workingDirectory, compileCommand);
  618. }
  619. // See if we need to use a compiler launcher like ccache or distcc
  620. std::string compilerLauncher;
  621. if (!compileCommands.empty() &&
  622. (lang == "C" || lang == "CXX" || lang == "Fortran" ||
  623. lang == "CUDA")) {
  624. std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER";
  625. const char* clauncher =
  626. this->GeneratorTarget->GetProperty(clauncher_prop);
  627. if (clauncher && *clauncher) {
  628. compilerLauncher = clauncher;
  629. }
  630. }
  631. // Maybe insert an include-what-you-use runner.
  632. if (!compileCommands.empty() && (lang == "C" || lang == "CXX")) {
  633. std::string const iwyu_prop = lang + "_INCLUDE_WHAT_YOU_USE";
  634. const char* iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
  635. std::string const tidy_prop = lang + "_CLANG_TIDY";
  636. const char* tidy = this->GeneratorTarget->GetProperty(tidy_prop);
  637. std::string const cpplint_prop = lang + "_CPPLINT";
  638. const char* cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
  639. std::string const cppcheck_prop = lang + "_CPPCHECK";
  640. const char* cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
  641. if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint) ||
  642. (cppcheck && *cppcheck)) {
  643. std::string run_iwyu = "$(CMAKE_COMMAND) -E __run_co_compile";
  644. if (!compilerLauncher.empty()) {
  645. // In __run_co_compile case the launcher command is supplied
  646. // via --launcher=<maybe-list> and consumed
  647. run_iwyu += " --launcher=";
  648. run_iwyu += this->LocalGenerator->EscapeForShell(compilerLauncher);
  649. compilerLauncher.clear();
  650. }
  651. if (iwyu && *iwyu) {
  652. run_iwyu += " --iwyu=";
  653. run_iwyu += this->LocalGenerator->EscapeForShell(iwyu);
  654. }
  655. if (tidy && *tidy) {
  656. run_iwyu += " --tidy=";
  657. run_iwyu += this->LocalGenerator->EscapeForShell(tidy);
  658. }
  659. if (cpplint && *cpplint) {
  660. run_iwyu += " --cpplint=";
  661. run_iwyu += this->LocalGenerator->EscapeForShell(cpplint);
  662. }
  663. if (cppcheck && *cppcheck) {
  664. run_iwyu += " --cppcheck=";
  665. run_iwyu += this->LocalGenerator->EscapeForShell(cppcheck);
  666. }
  667. if ((tidy && *tidy) || (cpplint && *cpplint) ||
  668. (cppcheck && *cppcheck)) {
  669. run_iwyu += " --source=";
  670. run_iwyu += sourceFile;
  671. }
  672. run_iwyu += " -- ";
  673. compileCommands.front().insert(0, run_iwyu);
  674. }
  675. }
  676. // If compiler launcher was specified and not consumed above, it
  677. // goes to the beginning of the command line.
  678. if (!compileCommands.empty() && !compilerLauncher.empty()) {
  679. std::vector<std::string> args;
  680. cmSystemTools::ExpandListArgument(compilerLauncher, args, true);
  681. for (std::string& i : args) {
  682. i = this->LocalGenerator->EscapeForShell(i);
  683. }
  684. compileCommands.front().insert(0, cmJoin(args, " ") + " ");
  685. }
  686. std::string launcher;
  687. {
  688. const char* val = this->LocalGenerator->GetRuleLauncher(
  689. this->GeneratorTarget, "RULE_LAUNCH_COMPILE");
  690. if (val && *val) {
  691. launcher = val;
  692. launcher += " ";
  693. }
  694. }
  695. // Expand placeholders in the commands.
  696. for (std::string& compileCommand : compileCommands) {
  697. compileCommand = launcher + compileCommand;
  698. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  699. compileCommand, vars);
  700. }
  701. // Change the command working directory to the local build tree.
  702. this->LocalGenerator->CreateCDCommand(
  703. compileCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  704. this->LocalGenerator->GetBinaryDirectory());
  705. commands.insert(commands.end(), compileCommands.begin(),
  706. compileCommands.end());
  707. }
  708. // Check for extra outputs created by the compilation.
  709. std::vector<std::string> outputs(1, relativeObj);
  710. if (const char* extra_outputs_str = source.GetProperty("OBJECT_OUTPUTS")) {
  711. // Register these as extra files to clean.
  712. cmSystemTools::ExpandListArgument(extra_outputs_str, outputs);
  713. this->CleanFiles.insert(this->CleanFiles.end(), outputs.begin() + 1,
  714. outputs.end());
  715. }
  716. // Write the rule.
  717. this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
  718. commands);
  719. bool do_preprocess_rules = lang_has_preprocessor &&
  720. this->LocalGenerator->GetCreatePreprocessedSourceRules();
  721. bool do_assembly_rules =
  722. lang_has_assembly && this->LocalGenerator->GetCreateAssemblySourceRules();
  723. if (do_preprocess_rules || do_assembly_rules) {
  724. std::vector<std::string> force_depends;
  725. force_depends.push_back("cmake_force");
  726. std::string::size_type dot_pos = relativeObj.rfind('.');
  727. std::string relativeObjBase = relativeObj.substr(0, dot_pos);
  728. dot_pos = obj.rfind('.');
  729. std::string objBase = obj.substr(0, dot_pos);
  730. if (do_preprocess_rules) {
  731. commands.clear();
  732. std::string relativeObjI = relativeObjBase + ".i";
  733. std::string objI = objBase + ".i";
  734. std::string preprocessEcho = "Preprocessing ";
  735. preprocessEcho += lang;
  736. preprocessEcho += " source to ";
  737. preprocessEcho += objI;
  738. this->LocalGenerator->AppendEcho(
  739. commands, preprocessEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  740. std::string preprocessRuleVar = "CMAKE_";
  741. preprocessRuleVar += lang;
  742. preprocessRuleVar += "_CREATE_PREPROCESSED_SOURCE";
  743. if (const char* preprocessRule =
  744. this->Makefile->GetDefinition(preprocessRuleVar)) {
  745. std::vector<std::string> preprocessCommands;
  746. cmSystemTools::ExpandListArgument(preprocessRule, preprocessCommands);
  747. std::string shellObjI = this->LocalGenerator->ConvertToOutputFormat(
  748. objI, cmOutputConverter::SHELL);
  749. vars.PreprocessedSource = shellObjI.c_str();
  750. // Expand placeholders in the commands.
  751. for (std::string& preprocessCommand : preprocessCommands) {
  752. // no launcher for preprocessor commands
  753. rulePlaceholderExpander->ExpandRuleVariables(
  754. this->LocalGenerator, preprocessCommand, vars);
  755. }
  756. this->LocalGenerator->CreateCDCommand(
  757. preprocessCommands,
  758. this->LocalGenerator->GetCurrentBinaryDirectory(),
  759. this->LocalGenerator->GetBinaryDirectory());
  760. commands.insert(commands.end(), preprocessCommands.begin(),
  761. preprocessCommands.end());
  762. } else {
  763. std::string cmd = "$(CMAKE_COMMAND) -E cmake_unimplemented_variable ";
  764. cmd += preprocessRuleVar;
  765. commands.push_back(std::move(cmd));
  766. }
  767. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  768. relativeObjI, force_depends,
  769. commands, false);
  770. }
  771. if (do_assembly_rules) {
  772. commands.clear();
  773. std::string relativeObjS = relativeObjBase + ".s";
  774. std::string objS = objBase + ".s";
  775. std::string assemblyEcho = "Compiling ";
  776. assemblyEcho += lang;
  777. assemblyEcho += " source to assembly ";
  778. assemblyEcho += objS;
  779. this->LocalGenerator->AppendEcho(
  780. commands, assemblyEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  781. std::string assemblyRuleVar = "CMAKE_";
  782. assemblyRuleVar += lang;
  783. assemblyRuleVar += "_CREATE_ASSEMBLY_SOURCE";
  784. if (const char* assemblyRule =
  785. this->Makefile->GetDefinition(assemblyRuleVar)) {
  786. std::vector<std::string> assemblyCommands;
  787. cmSystemTools::ExpandListArgument(assemblyRule, assemblyCommands);
  788. std::string shellObjS = this->LocalGenerator->ConvertToOutputFormat(
  789. objS, cmOutputConverter::SHELL);
  790. vars.AssemblySource = shellObjS.c_str();
  791. // Expand placeholders in the commands.
  792. for (std::string& assemblyCommand : assemblyCommands) {
  793. // no launcher for assembly commands
  794. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  795. assemblyCommand, vars);
  796. }
  797. this->LocalGenerator->CreateCDCommand(
  798. assemblyCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  799. this->LocalGenerator->GetBinaryDirectory());
  800. commands.insert(commands.end(), assemblyCommands.begin(),
  801. assemblyCommands.end());
  802. } else {
  803. std::string cmd = "$(CMAKE_COMMAND) -E cmake_unimplemented_variable ";
  804. cmd += assemblyRuleVar;
  805. commands.push_back(std::move(cmd));
  806. }
  807. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  808. relativeObjS, force_depends,
  809. commands, false);
  810. }
  811. }
  812. }
  813. void cmMakefileTargetGenerator::WriteTargetCleanRules()
  814. {
  815. std::vector<std::string> depends;
  816. std::vector<std::string> commands;
  817. // Construct the clean target name.
  818. std::string cleanTarget =
  819. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget);
  820. cleanTarget += "/clean";
  821. // Construct the clean command.
  822. this->LocalGenerator->AppendCleanCommand(commands, this->CleanFiles,
  823. this->GeneratorTarget);
  824. this->LocalGenerator->CreateCDCommand(
  825. commands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  826. this->LocalGenerator->GetBinaryDirectory());
  827. // Write the rule.
  828. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  829. cleanTarget, depends, commands, true);
  830. }
  831. bool cmMakefileTargetGenerator::WriteMakeRule(
  832. std::ostream& os, const char* comment,
  833. const std::vector<std::string>& outputs,
  834. const std::vector<std::string>& depends,
  835. const std::vector<std::string>& commands, bool in_help)
  836. {
  837. bool symbolic = false;
  838. if (outputs.empty()) {
  839. return symbolic;
  840. }
  841. // Check whether we need to bother checking for a symbolic output.
  842. bool need_symbolic = this->GlobalGenerator->GetNeedSymbolicMark();
  843. // Check whether the first output is marked as symbolic.
  844. if (need_symbolic) {
  845. if (cmSourceFile* sf = this->Makefile->GetSource(outputs[0])) {
  846. symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  847. }
  848. }
  849. // We always attach the actual commands to the first output.
  850. this->LocalGenerator->WriteMakeRule(os, comment, outputs[0], depends,
  851. commands, symbolic, in_help);
  852. // For single outputs, we are done.
  853. if (outputs.size() == 1) {
  854. return symbolic;
  855. }
  856. // For multiple outputs, make the extra ones depend on the first one.
  857. std::vector<std::string> const output_depends(1, outputs[0]);
  858. std::string binDir = this->LocalGenerator->GetBinaryDirectory();
  859. for (std::vector<std::string>::const_iterator o = outputs.begin() + 1;
  860. o != outputs.end(); ++o) {
  861. // Touch the extra output so "make" knows that it was updated,
  862. // but only if the output was actually created.
  863. std::string const out = this->LocalGenerator->ConvertToOutputFormat(
  864. this->LocalGenerator->MaybeConvertToRelativePath(binDir, *o),
  865. cmOutputConverter::SHELL);
  866. std::vector<std::string> output_commands;
  867. bool o_symbolic = false;
  868. if (need_symbolic) {
  869. if (cmSourceFile* sf = this->Makefile->GetSource(*o)) {
  870. o_symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  871. }
  872. }
  873. symbolic = symbolic && o_symbolic;
  874. if (!o_symbolic) {
  875. output_commands.push_back("@$(CMAKE_COMMAND) -E touch_nocreate " + out);
  876. }
  877. this->LocalGenerator->WriteMakeRule(os, nullptr, *o, output_depends,
  878. output_commands, o_symbolic, in_help);
  879. if (!o_symbolic) {
  880. // At build time, remove the first output if this one does not exist
  881. // so that "make" will rerun the real commands that create this one.
  882. MultipleOutputPairsType::value_type p(*o, outputs[0]);
  883. this->MultipleOutputPairs.insert(p);
  884. }
  885. }
  886. return symbolic;
  887. }
  888. void cmMakefileTargetGenerator::WriteTargetDependRules()
  889. {
  890. // must write the targets depend info file
  891. std::string dir =
  892. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  893. this->InfoFileNameFull = dir;
  894. this->InfoFileNameFull += "/DependInfo.cmake";
  895. this->InfoFileNameFull =
  896. this->LocalGenerator->ConvertToFullPath(this->InfoFileNameFull);
  897. this->InfoFileStream = new cmGeneratedFileStream(this->InfoFileNameFull);
  898. this->InfoFileStream->SetCopyIfDifferent(true);
  899. if (!*this->InfoFileStream) {
  900. return;
  901. }
  902. this->LocalGenerator->WriteDependLanguageInfo(*this->InfoFileStream,
  903. this->GeneratorTarget);
  904. // Store multiple output pairs in the depend info file.
  905. if (!this->MultipleOutputPairs.empty()) {
  906. /* clang-format off */
  907. *this->InfoFileStream
  908. << "\n"
  909. << "# Pairs of files generated by the same build rule.\n"
  910. << "set(CMAKE_MULTIPLE_OUTPUT_PAIRS\n";
  911. /* clang-format on */
  912. for (auto const& pi : this->MultipleOutputPairs) {
  913. *this->InfoFileStream
  914. << " " << cmOutputConverter::EscapeForCMake(pi.first) << " "
  915. << cmOutputConverter::EscapeForCMake(pi.second) << "\n";
  916. }
  917. *this->InfoFileStream << " )\n\n";
  918. }
  919. // Store list of targets linked directly or transitively.
  920. {
  921. /* clang-format off */
  922. *this->InfoFileStream
  923. << "\n"
  924. << "# Targets to which this target links.\n"
  925. << "set(CMAKE_TARGET_LINKED_INFO_FILES\n";
  926. /* clang-format on */
  927. std::vector<std::string> dirs = this->GetLinkedTargetDirectories();
  928. for (std::string const& d : dirs) {
  929. *this->InfoFileStream << " \"" << d << "/DependInfo.cmake\"\n";
  930. }
  931. *this->InfoFileStream << " )\n";
  932. }
  933. std::string const& working_dir =
  934. this->LocalGenerator->GetCurrentBinaryDirectory();
  935. /* clang-format off */
  936. *this->InfoFileStream
  937. << "\n"
  938. << "# Fortran module output directory.\n"
  939. << "set(CMAKE_Fortran_TARGET_MODULE_DIR \""
  940. << this->GeneratorTarget->GetFortranModuleDirectory(working_dir)
  941. << "\")\n";
  942. /* clang-format on */
  943. // and now write the rule to use it
  944. std::vector<std::string> depends;
  945. std::vector<std::string> commands;
  946. // Construct the name of the dependency generation target.
  947. std::string depTarget =
  948. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget);
  949. depTarget += "/depend";
  950. // Add a command to call CMake to scan dependencies. CMake will
  951. // touch the corresponding depends file after scanning dependencies.
  952. std::ostringstream depCmd;
  953. // TODO: Account for source file properties and directory-level
  954. // definitions when scanning for dependencies.
  955. #if !defined(_WIN32) || defined(__CYGWIN__)
  956. // This platform supports symlinks, so cmSystemTools will translate
  957. // paths. Make sure PWD is set to the original name of the home
  958. // output directory to help cmSystemTools to create the same
  959. // translation table for the dependency scanning process.
  960. depCmd << "cd "
  961. << (this->LocalGenerator->ConvertToOutputFormat(
  962. cmSystemTools::CollapseFullPath(
  963. this->LocalGenerator->GetBinaryDirectory()),
  964. cmOutputConverter::SHELL))
  965. << " && ";
  966. #endif
  967. // Generate a call this signature:
  968. //
  969. // cmake -E cmake_depends <generator>
  970. // <home-src-dir> <start-src-dir>
  971. // <home-out-dir> <start-out-dir>
  972. // <dep-info> --color=$(COLOR)
  973. //
  974. // This gives the dependency scanner enough information to recreate
  975. // the state of our local generator sufficiently for its needs.
  976. depCmd << "$(CMAKE_COMMAND) -E cmake_depends \""
  977. << this->GlobalGenerator->GetName() << "\" "
  978. << this->LocalGenerator->ConvertToOutputFormat(
  979. cmSystemTools::CollapseFullPath(
  980. this->LocalGenerator->GetSourceDirectory()),
  981. cmOutputConverter::SHELL)
  982. << " "
  983. << this->LocalGenerator->ConvertToOutputFormat(
  984. cmSystemTools::CollapseFullPath(
  985. this->LocalGenerator->GetCurrentSourceDirectory()),
  986. cmOutputConverter::SHELL)
  987. << " "
  988. << this->LocalGenerator->ConvertToOutputFormat(
  989. cmSystemTools::CollapseFullPath(
  990. this->LocalGenerator->GetBinaryDirectory()),
  991. cmOutputConverter::SHELL)
  992. << " "
  993. << this->LocalGenerator->ConvertToOutputFormat(
  994. cmSystemTools::CollapseFullPath(
  995. this->LocalGenerator->GetCurrentBinaryDirectory()),
  996. cmOutputConverter::SHELL)
  997. << " "
  998. << this->LocalGenerator->ConvertToOutputFormat(
  999. cmSystemTools::CollapseFullPath(this->InfoFileNameFull),
  1000. cmOutputConverter::SHELL);
  1001. if (this->LocalGenerator->GetColorMakefile()) {
  1002. depCmd << " --color=$(COLOR)";
  1003. }
  1004. commands.push_back(depCmd.str());
  1005. // Make sure all custom command outputs in this target are built.
  1006. if (this->CustomCommandDriver == OnDepends) {
  1007. this->DriveCustomCommands(depends);
  1008. }
  1009. // Write the rule.
  1010. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1011. depTarget, depends, commands, true);
  1012. }
  1013. void cmMakefileTargetGenerator::DriveCustomCommands(
  1014. std::vector<std::string>& depends)
  1015. {
  1016. // Depend on all custom command outputs.
  1017. std::vector<cmSourceFile*> sources;
  1018. this->GeneratorTarget->GetSourceFiles(
  1019. sources, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  1020. for (cmSourceFile* source : sources) {
  1021. if (cmCustomCommand* cc = source->GetCustomCommand()) {
  1022. cmCustomCommandGenerator ccg(*cc, this->ConfigName,
  1023. this->LocalGenerator);
  1024. const std::vector<std::string>& outputs = ccg.GetOutputs();
  1025. depends.insert(depends.end(), outputs.begin(), outputs.end());
  1026. }
  1027. }
  1028. }
  1029. void cmMakefileTargetGenerator::WriteObjectDependRules(
  1030. cmSourceFile const& source, std::vector<std::string>& depends)
  1031. {
  1032. // Create the list of dependencies known at cmake time. These are
  1033. // shared between the object file and dependency scanning rule.
  1034. depends.push_back(source.GetFullPath());
  1035. if (const char* objectDeps = source.GetProperty("OBJECT_DEPENDS")) {
  1036. cmSystemTools::ExpandListArgument(objectDeps, depends);
  1037. }
  1038. }
  1039. void cmMakefileTargetGenerator::GenerateCustomRuleFile(
  1040. cmCustomCommandGenerator const& ccg)
  1041. {
  1042. // Collect the commands.
  1043. std::vector<std::string> commands;
  1044. std::string comment = this->LocalGenerator->ConstructComment(ccg);
  1045. if (!comment.empty()) {
  1046. // add in a progress call if needed
  1047. this->NumberOfProgressActions++;
  1048. if (!this->NoRuleMessages) {
  1049. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  1050. this->MakeEchoProgress(progress);
  1051. this->LocalGenerator->AppendEcho(
  1052. commands, comment, cmLocalUnixMakefileGenerator3::EchoGenerate,
  1053. &progress);
  1054. }
  1055. }
  1056. // Now append the actual user-specified commands.
  1057. std::ostringstream content;
  1058. this->LocalGenerator->AppendCustomCommand(
  1059. commands, ccg, this->GeneratorTarget,
  1060. this->LocalGenerator->GetBinaryDirectory(), false, &content);
  1061. // Collect the dependencies.
  1062. std::vector<std::string> depends;
  1063. this->LocalGenerator->AppendCustomDepend(depends, ccg);
  1064. // Write the rule.
  1065. const std::vector<std::string>& outputs = ccg.GetOutputs();
  1066. bool symbolic = this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs,
  1067. depends, commands);
  1068. // If the rule has changed make sure the output is rebuilt.
  1069. if (!symbolic) {
  1070. this->GlobalGenerator->AddRuleHash(ccg.GetOutputs(), content.str());
  1071. }
  1072. // Setup implicit dependency scanning.
  1073. for (auto const& idi : ccg.GetCC().GetImplicitDepends()) {
  1074. std::string objFullPath = cmSystemTools::CollapseFullPath(outputs[0]);
  1075. std::string srcFullPath = cmSystemTools::CollapseFullPath(idi.second);
  1076. this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, idi.first,
  1077. objFullPath.c_str(),
  1078. srcFullPath.c_str());
  1079. }
  1080. }
  1081. void cmMakefileTargetGenerator::MakeEchoProgress(
  1082. cmLocalUnixMakefileGenerator3::EchoProgress& progress) const
  1083. {
  1084. progress.Dir = this->LocalGenerator->GetBinaryDirectory();
  1085. progress.Dir += cmake::GetCMakeFilesDirectory();
  1086. std::ostringstream progressArg;
  1087. progressArg << "$(CMAKE_PROGRESS_" << this->NumberOfProgressActions << ")";
  1088. progress.Arg = progressArg.str();
  1089. }
  1090. void cmMakefileTargetGenerator::WriteObjectsVariable(
  1091. std::string& variableName, std::string& variableNameExternal,
  1092. bool useWatcomQuote)
  1093. {
  1094. // Write a make variable assignment that lists all objects for the
  1095. // target.
  1096. variableName = this->LocalGenerator->CreateMakeVariable(
  1097. this->GeneratorTarget->GetName(), "_OBJECTS");
  1098. *this->BuildFileStream << "# Object files for target "
  1099. << this->GeneratorTarget->GetName() << "\n"
  1100. << variableName << " =";
  1101. std::string object;
  1102. const char* lineContinue =
  1103. this->Makefile->GetDefinition("CMAKE_MAKE_LINE_CONTINUE");
  1104. if (!lineContinue) {
  1105. lineContinue = "\\";
  1106. }
  1107. for (std::string const& obj : this->Objects) {
  1108. *this->BuildFileStream << " " << lineContinue << "\n";
  1109. *this->BuildFileStream
  1110. << cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1111. obj.c_str(), useWatcomQuote);
  1112. }
  1113. *this->BuildFileStream << "\n";
  1114. // Write a make variable assignment that lists all external objects
  1115. // for the target.
  1116. variableNameExternal = this->LocalGenerator->CreateMakeVariable(
  1117. this->GeneratorTarget->GetName(), "_EXTERNAL_OBJECTS");
  1118. /* clang-format off */
  1119. *this->BuildFileStream
  1120. << "\n"
  1121. << "# External object files for target "
  1122. << this->GeneratorTarget->GetName() << "\n"
  1123. << variableNameExternal << " =";
  1124. /* clang-format on */
  1125. std::string currentBinDir =
  1126. this->LocalGenerator->GetCurrentBinaryDirectory();
  1127. for (std::string const& obj : this->ExternalObjects) {
  1128. object =
  1129. this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, obj);
  1130. *this->BuildFileStream << " " << lineContinue << "\n";
  1131. *this->BuildFileStream
  1132. << cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1133. obj.c_str(), useWatcomQuote);
  1134. }
  1135. *this->BuildFileStream << "\n"
  1136. << "\n";
  1137. }
  1138. class cmMakefileTargetGeneratorObjectStrings
  1139. {
  1140. public:
  1141. cmMakefileTargetGeneratorObjectStrings(std::vector<std::string>& strings,
  1142. cmOutputConverter* outputConverter,
  1143. cmStateDirectory const& stateDir,
  1144. std::string::size_type limit)
  1145. : Strings(strings)
  1146. , OutputConverter(outputConverter)
  1147. , StateDir(stateDir)
  1148. , LengthLimit(limit)
  1149. {
  1150. this->Space = "";
  1151. }
  1152. void Feed(std::string const& obj)
  1153. {
  1154. // Construct the name of the next object.
  1155. this->NextObject = this->OutputConverter->ConvertToOutputFormat(
  1156. this->MaybeConvertToRelativePath(obj), cmOutputConverter::RESPONSE);
  1157. // Roll over to next string if the limit will be exceeded.
  1158. if (this->LengthLimit != std::string::npos &&
  1159. (this->CurrentString.length() + 1 + this->NextObject.length() >
  1160. this->LengthLimit)) {
  1161. this->Strings.push_back(this->CurrentString);
  1162. this->CurrentString.clear();
  1163. this->Space = "";
  1164. }
  1165. // Separate from previous object.
  1166. this->CurrentString += this->Space;
  1167. this->Space = " ";
  1168. // Append this object.
  1169. this->CurrentString += this->NextObject;
  1170. }
  1171. void Done() { this->Strings.push_back(this->CurrentString); }
  1172. private:
  1173. std::string MaybeConvertToRelativePath(std::string const& obj)
  1174. {
  1175. if (!cmOutputConverter::ContainedInDirectory(
  1176. this->StateDir.GetCurrentBinary(), obj, this->StateDir)) {
  1177. return obj;
  1178. }
  1179. return cmSystemTools::ForceToRelativePath(
  1180. this->StateDir.GetCurrentBinary(), obj);
  1181. }
  1182. std::vector<std::string>& Strings;
  1183. cmOutputConverter* OutputConverter;
  1184. cmStateDirectory StateDir;
  1185. std::string::size_type LengthLimit;
  1186. std::string CurrentString;
  1187. std::string NextObject;
  1188. const char* Space;
  1189. };
  1190. void cmMakefileTargetGenerator::WriteObjectsStrings(
  1191. std::vector<std::string>& objStrings, std::string::size_type limit)
  1192. {
  1193. cmMakefileTargetGeneratorObjectStrings helper(
  1194. objStrings, this->LocalGenerator,
  1195. this->LocalGenerator->GetStateSnapshot().GetDirectory(), limit);
  1196. for (std::string const& obj : this->Objects) {
  1197. helper.Feed(obj);
  1198. }
  1199. for (std::string const& obj : this->ExternalObjects) {
  1200. helper.Feed(obj);
  1201. }
  1202. helper.Done();
  1203. }
  1204. void cmMakefileTargetGenerator::WriteTargetDriverRule(
  1205. const std::string& main_output, bool relink)
  1206. {
  1207. // Compute the name of the driver target.
  1208. std::string dir =
  1209. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget);
  1210. std::string buildTargetRuleName = dir;
  1211. buildTargetRuleName += relink ? "/preinstall" : "/build";
  1212. buildTargetRuleName = this->LocalGenerator->MaybeConvertToRelativePath(
  1213. this->LocalGenerator->GetBinaryDirectory(), buildTargetRuleName);
  1214. // Build the list of target outputs to drive.
  1215. std::vector<std::string> depends;
  1216. depends.push_back(main_output);
  1217. const char* comment = nullptr;
  1218. if (relink) {
  1219. // Setup the comment for the preinstall driver.
  1220. comment = "Rule to relink during preinstall.";
  1221. } else {
  1222. // Setup the comment for the main build driver.
  1223. comment = "Rule to build all files generated by this target.";
  1224. // Make sure all custom command outputs in this target are built.
  1225. if (this->CustomCommandDriver == OnBuild) {
  1226. this->DriveCustomCommands(depends);
  1227. }
  1228. // Make sure the extra files are built.
  1229. depends.insert(depends.end(), this->ExtraFiles.begin(),
  1230. this->ExtraFiles.end());
  1231. }
  1232. // Write the driver rule.
  1233. std::vector<std::string> no_commands;
  1234. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, comment,
  1235. buildTargetRuleName, depends,
  1236. no_commands, true);
  1237. }
  1238. void cmMakefileTargetGenerator::AppendTargetDepends(
  1239. std::vector<std::string>& depends)
  1240. {
  1241. // Static libraries never depend on anything for linking.
  1242. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  1243. return;
  1244. }
  1245. // Loop over all library dependencies.
  1246. const char* cfg = this->LocalGenerator->GetConfigName().c_str();
  1247. if (cmComputeLinkInformation* cli =
  1248. this->GeneratorTarget->GetLinkInformation(cfg)) {
  1249. std::vector<std::string> const& libDeps = cli->GetDepends();
  1250. depends.insert(depends.end(), libDeps.begin(), libDeps.end());
  1251. }
  1252. }
  1253. void cmMakefileTargetGenerator::AppendObjectDepends(
  1254. std::vector<std::string>& depends)
  1255. {
  1256. // Add dependencies on the compiled object files.
  1257. std::string const& relPath =
  1258. this->LocalGenerator->GetHomeRelativeOutputPath();
  1259. for (std::string const& obj : this->Objects) {
  1260. std::string objTarget = relPath;
  1261. objTarget += obj;
  1262. depends.push_back(std::move(objTarget));
  1263. }
  1264. // Add dependencies on the external object files.
  1265. depends.insert(depends.end(), this->ExternalObjects.begin(),
  1266. this->ExternalObjects.end());
  1267. // Add a dependency on the rule file itself.
  1268. this->LocalGenerator->AppendRuleDepend(depends,
  1269. this->BuildFileNameFull.c_str());
  1270. }
  1271. void cmMakefileTargetGenerator::AppendLinkDepends(
  1272. std::vector<std::string>& depends, const std::string& linkLanguage)
  1273. {
  1274. this->AppendObjectDepends(depends);
  1275. // Add dependencies on targets that must be built first.
  1276. this->AppendTargetDepends(depends);
  1277. // Add a dependency on the link definitions file, if any.
  1278. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1279. this->GeneratorTarget->GetModuleDefinitionInfo(
  1280. this->GetConfigName())) {
  1281. for (cmSourceFile const* src : mdi->Sources) {
  1282. depends.push_back(src->GetFullPath());
  1283. }
  1284. }
  1285. // Add a dependency on user-specified manifest files, if any.
  1286. std::vector<cmSourceFile const*> manifest_srcs;
  1287. this->GeneratorTarget->GetManifests(manifest_srcs, this->ConfigName);
  1288. for (cmSourceFile const* manifest_src : manifest_srcs) {
  1289. depends.push_back(manifest_src->GetFullPath());
  1290. }
  1291. // Add user-specified dependencies.
  1292. this->GeneratorTarget->GetLinkDepends(depends, this->ConfigName,
  1293. linkLanguage);
  1294. }
  1295. std::string cmMakefileTargetGenerator::GetLinkRule(
  1296. const std::string& linkRuleVar)
  1297. {
  1298. std::string linkRule = this->Makefile->GetRequiredDefinition(linkRuleVar);
  1299. if (this->GeneratorTarget->HasImplibGNUtoMS(this->ConfigName)) {
  1300. std::string ruleVar = "CMAKE_";
  1301. ruleVar += this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
  1302. ruleVar += "_GNUtoMS_RULE";
  1303. if (const char* rule = this->Makefile->GetDefinition(ruleVar)) {
  1304. linkRule += rule;
  1305. }
  1306. }
  1307. return linkRule;
  1308. }
  1309. void cmMakefileTargetGenerator::CloseFileStreams()
  1310. {
  1311. delete this->BuildFileStream;
  1312. delete this->InfoFileStream;
  1313. delete this->FlagFileStream;
  1314. }
  1315. void cmMakefileTargetGenerator::CreateLinkScript(
  1316. const char* name, std::vector<std::string> const& link_commands,
  1317. std::vector<std::string>& makefile_commands,
  1318. std::vector<std::string>& makefile_depends)
  1319. {
  1320. // Create the link script file.
  1321. std::string linkScriptName = this->TargetBuildDirectoryFull;
  1322. linkScriptName += "/";
  1323. linkScriptName += name;
  1324. cmGeneratedFileStream linkScriptStream(linkScriptName);
  1325. linkScriptStream.SetCopyIfDifferent(true);
  1326. for (std::string const& link_command : link_commands) {
  1327. // Do not write out empty commands or commands beginning in the
  1328. // shell no-op ":".
  1329. if (!link_command.empty() && link_command[0] != ':') {
  1330. linkScriptStream << link_command << "\n";
  1331. }
  1332. }
  1333. // Create the makefile command to invoke the link script.
  1334. std::string link_command = "$(CMAKE_COMMAND) -E cmake_link_script ";
  1335. link_command += this->LocalGenerator->ConvertToOutputFormat(
  1336. this->LocalGenerator->MaybeConvertToRelativePath(
  1337. this->LocalGenerator->GetCurrentBinaryDirectory(), linkScriptName),
  1338. cmOutputConverter::SHELL);
  1339. link_command += " --verbose=$(VERBOSE)";
  1340. makefile_commands.push_back(std::move(link_command));
  1341. makefile_depends.push_back(std::move(linkScriptName));
  1342. }
  1343. bool cmMakefileTargetGenerator::CheckUseResponseFileForObjects(
  1344. std::string const& l) const
  1345. {
  1346. // Check for an explicit setting one way or the other.
  1347. std::string const responseVar =
  1348. "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_OBJECTS";
  1349. if (const char* val = this->Makefile->GetDefinition(responseVar)) {
  1350. if (*val) {
  1351. return cmSystemTools::IsOn(val);
  1352. }
  1353. }
  1354. // Check for a system limit.
  1355. if (size_t const limit = cmSystemTools::CalculateCommandLineLengthLimit()) {
  1356. // Compute the total length of our list of object files with room
  1357. // for argument separation and quoting. This does not convert paths
  1358. // relative to CMAKE_CURRENT_BINARY_DIR like the final list will be, so the
  1359. // actual list will likely be much shorter than this. However, in the
  1360. // worst case all objects will remain as absolute paths.
  1361. size_t length = 0;
  1362. for (std::string const& obj : this->Objects) {
  1363. length += obj.size() + 3;
  1364. }
  1365. for (std::string const& ext_obj : this->ExternalObjects) {
  1366. length += ext_obj.size() + 3;
  1367. }
  1368. // We need to guarantee room for both objects and libraries, so
  1369. // if the objects take up more than half then use a response file
  1370. // for them.
  1371. if (length > (limit / 2)) {
  1372. return true;
  1373. }
  1374. }
  1375. // We do not need a response file for objects.
  1376. return false;
  1377. }
  1378. bool cmMakefileTargetGenerator::CheckUseResponseFileForLibraries(
  1379. std::string const& l) const
  1380. {
  1381. // Check for an explicit setting one way or the other.
  1382. std::string const responseVar =
  1383. "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_LIBRARIES";
  1384. if (const char* val = this->Makefile->GetDefinition(responseVar)) {
  1385. if (*val) {
  1386. return cmSystemTools::IsOn(val);
  1387. }
  1388. }
  1389. // We do not need a response file for libraries.
  1390. return false;
  1391. }
  1392. std::string cmMakefileTargetGenerator::CreateResponseFile(
  1393. const char* name, std::string const& options,
  1394. std::vector<std::string>& makefile_depends)
  1395. {
  1396. // Create the response file.
  1397. std::string responseFileNameFull = this->TargetBuildDirectoryFull;
  1398. responseFileNameFull += "/";
  1399. responseFileNameFull += name;
  1400. cmGeneratedFileStream responseStream(responseFileNameFull);
  1401. responseStream.SetCopyIfDifferent(true);
  1402. responseStream << options << "\n";
  1403. // Add a dependency so the target will rebuild when the set of
  1404. // objects changes.
  1405. makefile_depends.push_back(std::move(responseFileNameFull));
  1406. // Construct the name to be used on the command line.
  1407. std::string responseFileName = this->TargetBuildDirectory;
  1408. responseFileName += "/";
  1409. responseFileName += name;
  1410. return responseFileName;
  1411. }
  1412. cmLinkLineComputer* cmMakefileTargetGenerator::CreateLinkLineComputer(
  1413. cmOutputConverter* outputConverter, cmStateDirectory const& stateDir)
  1414. {
  1415. if (this->Makefile->IsOn("MSVC60")) {
  1416. return this->GlobalGenerator->CreateMSVC60LinkLineComputer(outputConverter,
  1417. stateDir);
  1418. }
  1419. return this->GlobalGenerator->CreateLinkLineComputer(outputConverter,
  1420. stateDir);
  1421. }
  1422. void cmMakefileTargetGenerator::CreateLinkLibs(
  1423. cmLinkLineComputer* linkLineComputer, std::string& linkLibs,
  1424. bool useResponseFile, std::vector<std::string>& makefile_depends)
  1425. {
  1426. std::string frameworkPath;
  1427. std::string linkPath;
  1428. std::string config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  1429. cmComputeLinkInformation* pcli =
  1430. this->GeneratorTarget->GetLinkInformation(config);
  1431. this->LocalGenerator->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1432. frameworkPath, linkPath);
  1433. linkLibs = frameworkPath + linkPath + linkLibs;
  1434. if (useResponseFile &&
  1435. linkLibs.find_first_not_of(' ') != std::string::npos) {
  1436. // Lookup the response file reference flag.
  1437. std::string responseFlagVar = "CMAKE_";
  1438. responseFlagVar +=
  1439. this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
  1440. responseFlagVar += "_RESPONSE_FILE_LINK_FLAG";
  1441. const char* responseFlag = this->Makefile->GetDefinition(responseFlagVar);
  1442. if (!responseFlag) {
  1443. responseFlag = "@";
  1444. }
  1445. // Create this response file.
  1446. std::string link_rsp =
  1447. this->CreateResponseFile("linklibs.rsp", linkLibs, makefile_depends);
  1448. // Reference the response file.
  1449. linkLibs = responseFlag;
  1450. linkLibs += this->LocalGenerator->ConvertToOutputFormat(
  1451. link_rsp, cmOutputConverter::SHELL);
  1452. }
  1453. }
  1454. void cmMakefileTargetGenerator::CreateObjectLists(
  1455. bool useLinkScript, bool useArchiveRules, bool useResponseFile,
  1456. std::string& buildObjs, std::vector<std::string>& makefile_depends,
  1457. bool useWatcomQuote)
  1458. {
  1459. std::string variableName;
  1460. std::string variableNameExternal;
  1461. this->WriteObjectsVariable(variableName, variableNameExternal,
  1462. useWatcomQuote);
  1463. if (useResponseFile) {
  1464. // MSVC response files cannot exceed 128K.
  1465. std::string::size_type const responseFileLimit = 131000;
  1466. // Construct the individual object list strings.
  1467. std::vector<std::string> object_strings;
  1468. this->WriteObjectsStrings(object_strings, responseFileLimit);
  1469. // Lookup the response file reference flag.
  1470. std::string responseFlagVar = "CMAKE_";
  1471. responseFlagVar +=
  1472. this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
  1473. responseFlagVar += "_RESPONSE_FILE_LINK_FLAG";
  1474. const char* responseFlag = this->Makefile->GetDefinition(responseFlagVar);
  1475. if (!responseFlag) {
  1476. responseFlag = "@";
  1477. }
  1478. // Write a response file for each string.
  1479. const char* sep = "";
  1480. for (unsigned int i = 0; i < object_strings.size(); ++i) {
  1481. // Number the response files.
  1482. char rsp[32];
  1483. sprintf(rsp, "objects%u.rsp", i + 1);
  1484. // Create this response file.
  1485. std::string objects_rsp =
  1486. this->CreateResponseFile(rsp, object_strings[i], makefile_depends);
  1487. // Separate from previous response file references.
  1488. buildObjs += sep;
  1489. sep = " ";
  1490. // Reference the response file.
  1491. buildObjs += responseFlag;
  1492. buildObjs += this->LocalGenerator->ConvertToOutputFormat(
  1493. objects_rsp, cmOutputConverter::SHELL);
  1494. }
  1495. } else if (useLinkScript) {
  1496. if (!useArchiveRules) {
  1497. std::vector<std::string> objStrings;
  1498. this->WriteObjectsStrings(objStrings);
  1499. buildObjs = objStrings[0];
  1500. }
  1501. } else {
  1502. buildObjs = "$(";
  1503. buildObjs += variableName;
  1504. buildObjs += ") $(";
  1505. buildObjs += variableNameExternal;
  1506. buildObjs += ")";
  1507. }
  1508. }
  1509. void cmMakefileTargetGenerator::AddIncludeFlags(std::string& flags,
  1510. const std::string& lang)
  1511. {
  1512. std::string responseVar = "CMAKE_";
  1513. responseVar += lang;
  1514. responseVar += "_USE_RESPONSE_FILE_FOR_INCLUDES";
  1515. bool useResponseFile = this->Makefile->IsOn(responseVar);
  1516. std::vector<std::string> includes;
  1517. const std::string& config =
  1518. this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  1519. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1520. lang, config);
  1521. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  1522. includes, this->GeneratorTarget, lang, false, useResponseFile, config);
  1523. if (includeFlags.empty()) {
  1524. return;
  1525. }
  1526. if (useResponseFile) {
  1527. std::string const responseFlagVar =
  1528. "CMAKE_" + lang + "_RESPONSE_FILE_FLAG";
  1529. std::string responseFlag =
  1530. this->Makefile->GetSafeDefinition(responseFlagVar);
  1531. if (responseFlag.empty()) {
  1532. responseFlag = "@";
  1533. }
  1534. std::string name = "includes_";
  1535. name += lang;
  1536. name += ".rsp";
  1537. std::string arg = std::move(responseFlag) +
  1538. this->CreateResponseFile(name.c_str(), includeFlags,
  1539. this->FlagFileDepends[lang]);
  1540. this->LocalGenerator->AppendFlags(flags, arg);
  1541. } else {
  1542. this->LocalGenerator->AppendFlags(flags, includeFlags);
  1543. }
  1544. }
  1545. void cmMakefileTargetGenerator::GenDefFile(
  1546. std::vector<std::string>& real_link_commands)
  1547. {
  1548. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1549. this->GeneratorTarget->GetModuleDefinitionInfo(this->GetConfigName());
  1550. if (!mdi || !mdi->DefFileGenerated) {
  1551. return;
  1552. }
  1553. std::string cmd = cmSystemTools::GetCMakeCommand();
  1554. cmd =
  1555. this->LocalGenerator->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
  1556. cmd += " -E __create_def ";
  1557. cmd += this->LocalGenerator->ConvertToOutputFormat(
  1558. this->LocalGenerator->MaybeConvertToRelativePath(
  1559. this->LocalGenerator->GetCurrentBinaryDirectory(), mdi->DefFile),
  1560. cmOutputConverter::SHELL);
  1561. cmd += " ";
  1562. std::string objlist_file = mdi->DefFile + ".objs";
  1563. cmd += this->LocalGenerator->ConvertToOutputFormat(
  1564. this->LocalGenerator->MaybeConvertToRelativePath(
  1565. this->LocalGenerator->GetCurrentBinaryDirectory(), objlist_file),
  1566. cmOutputConverter::SHELL);
  1567. real_link_commands.insert(real_link_commands.begin(), cmd);
  1568. // create a list of obj files for the -E __create_def to read
  1569. cmGeneratedFileStream fout(objlist_file);
  1570. if (mdi->WindowsExportAllSymbols) {
  1571. for (std::string const& obj : this->Objects) {
  1572. if (cmHasLiteralSuffix(obj, ".obj")) {
  1573. fout << obj << "\n";
  1574. }
  1575. }
  1576. for (std::string const& obj : this->ExternalObjects) {
  1577. fout << obj << "\n";
  1578. }
  1579. }
  1580. for (cmSourceFile const* src : mdi->Sources) {
  1581. fout << src->GetFullPath() << "\n";
  1582. }
  1583. }