cmMakefileTargetGenerator.cxx 67 KB

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