cmNinjaNormalTargetGenerator.cxx 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  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 "cmNinjaNormalTargetGenerator.h"
  4. #include <algorithm>
  5. #include <assert.h>
  6. #include <iterator>
  7. #include <map>
  8. #include <set>
  9. #include <sstream>
  10. #include <utility>
  11. #include "cm_memory.hxx"
  12. #include "cmAlgorithms.h"
  13. #include "cmCustomCommand.h" // IWYU pragma: keep
  14. #include "cmCustomCommandGenerator.h"
  15. #include "cmGeneratedFileStream.h"
  16. #include "cmGeneratorTarget.h"
  17. #include "cmGlobalNinjaGenerator.h"
  18. #include "cmLinkLineComputer.h"
  19. #include "cmLinkLineDeviceComputer.h"
  20. #include "cmLocalGenerator.h"
  21. #include "cmLocalNinjaGenerator.h"
  22. #include "cmMakefile.h"
  23. #include "cmNinjaLinkLineDeviceComputer.h"
  24. #include "cmNinjaTypes.h"
  25. #include "cmOSXBundleGenerator.h"
  26. #include "cmOutputConverter.h"
  27. #include "cmRulePlaceholderExpander.h"
  28. #include "cmSourceFile.h"
  29. #include "cmState.h"
  30. #include "cmStateDirectory.h"
  31. #include "cmStateSnapshot.h"
  32. #include "cmStateTypes.h"
  33. #include "cmStringAlgorithms.h"
  34. #include "cmSystemTools.h"
  35. cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator(
  36. cmGeneratorTarget* target)
  37. : cmNinjaTargetGenerator(target)
  38. , TargetLinkLanguage("")
  39. {
  40. this->TargetLinkLanguage = target->GetLinkerLanguage(this->GetConfigName());
  41. if (target->GetType() == cmStateEnums::EXECUTABLE) {
  42. this->TargetNames = this->GetGeneratorTarget()->GetExecutableNames(
  43. GetLocalGenerator()->GetConfigName());
  44. } else {
  45. this->TargetNames = this->GetGeneratorTarget()->GetLibraryNames(
  46. GetLocalGenerator()->GetConfigName());
  47. }
  48. if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  49. // on Windows the output dir is already needed at compile time
  50. // ensure the directory exists (OutDir test)
  51. EnsureDirectoryExists(target->GetDirectory(this->GetConfigName()));
  52. }
  53. this->OSXBundleGenerator =
  54. cm::make_unique<cmOSXBundleGenerator>(target, this->GetConfigName());
  55. this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders);
  56. }
  57. cmNinjaNormalTargetGenerator::~cmNinjaNormalTargetGenerator() = default;
  58. void cmNinjaNormalTargetGenerator::Generate()
  59. {
  60. if (this->TargetLinkLanguage.empty()) {
  61. cmSystemTools::Error("CMake can not determine linker language for "
  62. "target: " +
  63. this->GetGeneratorTarget()->GetName());
  64. return;
  65. }
  66. // Write the rules for each language.
  67. this->WriteLanguagesRules();
  68. // Write the build statements
  69. this->WriteObjectBuildStatements();
  70. if (this->GetGeneratorTarget()->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  71. this->WriteObjectLibStatement();
  72. } else {
  73. // If this target has cuda language link inputs, and we need to do
  74. // device linking
  75. this->WriteDeviceLinkStatement();
  76. this->WriteLinkStatement();
  77. }
  78. this->AdditionalCleanFiles();
  79. }
  80. void cmNinjaNormalTargetGenerator::WriteLanguagesRules()
  81. {
  82. #ifdef NINJA_GEN_VERBOSE_FILES
  83. cmGlobalNinjaGenerator::WriteDivider(this->GetRulesFileStream());
  84. this->GetRulesFileStream()
  85. << "# Rules for each languages for "
  86. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  87. << " target " << this->GetTargetName() << "\n\n";
  88. #endif
  89. // Write rules for languages compiled in this target.
  90. std::set<std::string> languages;
  91. std::vector<cmSourceFile const*> sourceFiles;
  92. this->GetGeneratorTarget()->GetObjectSources(
  93. sourceFiles, this->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  94. for (cmSourceFile const* sf : sourceFiles) {
  95. std::string const lang = sf->GetLanguage();
  96. if (!lang.empty()) {
  97. languages.insert(lang);
  98. }
  99. }
  100. for (std::string const& language : languages) {
  101. this->WriteLanguageRules(language);
  102. }
  103. }
  104. const char* cmNinjaNormalTargetGenerator::GetVisibleTypeName() const
  105. {
  106. switch (this->GetGeneratorTarget()->GetType()) {
  107. case cmStateEnums::STATIC_LIBRARY:
  108. return "static library";
  109. case cmStateEnums::SHARED_LIBRARY:
  110. return "shared library";
  111. case cmStateEnums::MODULE_LIBRARY:
  112. if (this->GetGeneratorTarget()->IsCFBundleOnApple()) {
  113. return "CFBundle shared module";
  114. } else {
  115. return "shared module";
  116. }
  117. case cmStateEnums::EXECUTABLE:
  118. return "executable";
  119. default:
  120. return nullptr;
  121. }
  122. }
  123. std::string cmNinjaNormalTargetGenerator::LanguageLinkerRule() const
  124. {
  125. return this->TargetLinkLanguage + "_" +
  126. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()) +
  127. "_LINKER__" +
  128. cmGlobalNinjaGenerator::EncodeRuleName(
  129. this->GetGeneratorTarget()->GetName());
  130. }
  131. std::string cmNinjaNormalTargetGenerator::LanguageLinkerDeviceRule() const
  132. {
  133. return this->TargetLinkLanguage + "_" +
  134. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()) +
  135. "_DEVICE_LINKER__" +
  136. cmGlobalNinjaGenerator::EncodeRuleName(
  137. this->GetGeneratorTarget()->GetName());
  138. }
  139. struct cmNinjaRemoveNoOpCommands
  140. {
  141. bool operator()(std::string const& cmd)
  142. {
  143. return cmd.empty() || cmd[0] == ':';
  144. }
  145. };
  146. void cmNinjaNormalTargetGenerator::WriteDeviceLinkRule(bool useResponseFile)
  147. {
  148. cmNinjaRule rule(this->LanguageLinkerDeviceRule());
  149. if (!this->GetGlobalGenerator()->HasRule(rule.Name)) {
  150. cmRulePlaceholderExpander::RuleVariables vars;
  151. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  152. vars.CMTargetType =
  153. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType());
  154. vars.Language = "CUDA";
  155. // build response file name
  156. std::string responseFlag = this->GetMakefile()->GetSafeDefinition(
  157. "CMAKE_CUDA_RESPONSE_FILE_LINK_FLAG");
  158. if (!useResponseFile || responseFlag.empty()) {
  159. vars.Objects = "$in";
  160. vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
  161. } else {
  162. rule.RspFile = "$RSP_FILE";
  163. responseFlag += rule.RspFile;
  164. // build response file content
  165. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  166. rule.RspContent = "$in";
  167. } else {
  168. rule.RspContent = "$in_newline";
  169. }
  170. rule.RspContent += " $LINK_LIBRARIES";
  171. vars.Objects = responseFlag.c_str();
  172. vars.LinkLibraries = "";
  173. }
  174. vars.ObjectDir = "$OBJECT_DIR";
  175. vars.Target = "$TARGET_FILE";
  176. vars.SONameFlag = "$SONAME_FLAG";
  177. vars.TargetSOName = "$SONAME";
  178. vars.TargetPDB = "$TARGET_PDB";
  179. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  180. vars.Flags = "$FLAGS";
  181. vars.LinkFlags = "$LINK_FLAGS";
  182. vars.Manifests = "$MANIFESTS";
  183. std::string langFlags;
  184. if (this->GetGeneratorTarget()->GetType() != cmStateEnums::EXECUTABLE) {
  185. langFlags += "$LANGUAGE_COMPILE_FLAGS $ARCH_FLAGS";
  186. vars.LanguageCompileFlags = langFlags.c_str();
  187. }
  188. std::string launcher;
  189. const char* val = this->GetLocalGenerator()->GetRuleLauncher(
  190. this->GetGeneratorTarget(), "RULE_LAUNCH_LINK");
  191. if (val && *val) {
  192. launcher = val;
  193. launcher += " ";
  194. }
  195. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  196. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  197. // Rule for linking library/executable.
  198. std::vector<std::string> linkCmds = this->ComputeDeviceLinkCmd();
  199. for (std::string& linkCmd : linkCmds) {
  200. linkCmd = cmStrCat(launcher, linkCmd);
  201. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  202. linkCmd, vars);
  203. }
  204. // If there is no ranlib the command will be ":". Skip it.
  205. cmEraseIf(linkCmds, cmNinjaRemoveNoOpCommands());
  206. rule.Command = this->GetLocalGenerator()->BuildCommandLine(linkCmds);
  207. // Write the linker rule with response file if needed.
  208. rule.Comment = "Rule for linking ";
  209. rule.Comment += this->TargetLinkLanguage;
  210. rule.Comment += " ";
  211. rule.Comment += this->GetVisibleTypeName();
  212. rule.Comment += ".";
  213. rule.Description = "Linking ";
  214. rule.Description += this->TargetLinkLanguage;
  215. rule.Description += " ";
  216. rule.Description += this->GetVisibleTypeName();
  217. rule.Description += " $TARGET_FILE";
  218. rule.Restat = "$RESTAT";
  219. this->GetGlobalGenerator()->AddRule(rule);
  220. }
  221. }
  222. void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
  223. {
  224. cmStateEnums::TargetType targetType = this->GetGeneratorTarget()->GetType();
  225. std::string linkRuleName = this->LanguageLinkerRule();
  226. if (!this->GetGlobalGenerator()->HasRule(linkRuleName)) {
  227. cmNinjaRule rule(std::move(linkRuleName));
  228. cmRulePlaceholderExpander::RuleVariables vars;
  229. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  230. vars.CMTargetType = cmState::GetTargetTypeName(targetType);
  231. vars.Language = this->TargetLinkLanguage.c_str();
  232. if (this->TargetLinkLanguage == "Swift") {
  233. vars.SwiftLibraryName = "$SWIFT_LIBRARY_NAME";
  234. vars.SwiftModule = "$SWIFT_MODULE";
  235. vars.SwiftModuleName = "$SWIFT_MODULE_NAME";
  236. vars.SwiftOutputFileMap = "$SWIFT_OUTPUT_FILE_MAP";
  237. vars.SwiftSources = "$SWIFT_SOURCES";
  238. vars.Defines = "$DEFINES";
  239. vars.Flags = "$FLAGS";
  240. vars.Includes = "$INCLUDES";
  241. }
  242. std::string responseFlag;
  243. std::string cmakeVarLang = "CMAKE_";
  244. cmakeVarLang += this->TargetLinkLanguage;
  245. // build response file name
  246. std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
  247. const char* flag = GetMakefile()->GetDefinition(cmakeLinkVar);
  248. if (flag) {
  249. responseFlag = flag;
  250. } else if (this->TargetLinkLanguage != "CUDA") {
  251. responseFlag = "@";
  252. }
  253. if (!useResponseFile || responseFlag.empty()) {
  254. vars.Objects = "$in";
  255. vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
  256. } else {
  257. rule.RspFile = "$RSP_FILE";
  258. responseFlag += rule.RspFile;
  259. // build response file content
  260. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  261. rule.RspContent = "$in";
  262. } else {
  263. rule.RspContent = "$in_newline";
  264. }
  265. rule.RspContent += " $LINK_PATH $LINK_LIBRARIES";
  266. if (this->TargetLinkLanguage == "Swift") {
  267. vars.SwiftSources = responseFlag.c_str();
  268. } else {
  269. vars.Objects = responseFlag.c_str();
  270. }
  271. vars.LinkLibraries = "";
  272. }
  273. vars.ObjectDir = "$OBJECT_DIR";
  274. vars.Target = "$TARGET_FILE";
  275. vars.SONameFlag = "$SONAME_FLAG";
  276. vars.TargetSOName = "$SONAME";
  277. vars.TargetInstallNameDir = "$INSTALLNAME_DIR";
  278. vars.TargetPDB = "$TARGET_PDB";
  279. // Setup the target version.
  280. std::string targetVersionMajor;
  281. std::string targetVersionMinor;
  282. {
  283. std::ostringstream majorStream;
  284. std::ostringstream minorStream;
  285. int major;
  286. int minor;
  287. this->GetGeneratorTarget()->GetTargetVersion(major, minor);
  288. majorStream << major;
  289. minorStream << minor;
  290. targetVersionMajor = majorStream.str();
  291. targetVersionMinor = minorStream.str();
  292. }
  293. vars.TargetVersionMajor = targetVersionMajor.c_str();
  294. vars.TargetVersionMinor = targetVersionMinor.c_str();
  295. vars.Flags = "$FLAGS";
  296. vars.LinkFlags = "$LINK_FLAGS";
  297. vars.Manifests = "$MANIFESTS";
  298. std::string langFlags;
  299. if (targetType != cmStateEnums::EXECUTABLE) {
  300. langFlags += "$LANGUAGE_COMPILE_FLAGS $ARCH_FLAGS";
  301. vars.LanguageCompileFlags = langFlags.c_str();
  302. }
  303. std::string launcher;
  304. const char* val = this->GetLocalGenerator()->GetRuleLauncher(
  305. this->GetGeneratorTarget(), "RULE_LAUNCH_LINK");
  306. if (val && *val) {
  307. launcher = val;
  308. launcher += " ";
  309. }
  310. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  311. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  312. // Rule for linking library/executable.
  313. std::vector<std::string> linkCmds = this->ComputeLinkCmd();
  314. for (std::string& linkCmd : linkCmds) {
  315. linkCmd = cmStrCat(launcher, linkCmd);
  316. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  317. linkCmd, vars);
  318. }
  319. // If there is no ranlib the command will be ":". Skip it.
  320. cmEraseIf(linkCmds, cmNinjaRemoveNoOpCommands());
  321. linkCmds.insert(linkCmds.begin(), "$PRE_LINK");
  322. linkCmds.emplace_back("$POST_BUILD");
  323. rule.Command = this->GetLocalGenerator()->BuildCommandLine(linkCmds);
  324. // Write the linker rule with response file if needed.
  325. rule.Comment = "Rule for linking ";
  326. rule.Comment += this->TargetLinkLanguage;
  327. rule.Comment += " ";
  328. rule.Comment += this->GetVisibleTypeName();
  329. rule.Comment += ".";
  330. rule.Description = "Linking ";
  331. rule.Description += this->TargetLinkLanguage;
  332. rule.Description += " ";
  333. rule.Description += this->GetVisibleTypeName();
  334. rule.Description += " $TARGET_FILE";
  335. rule.Restat = "$RESTAT";
  336. this->GetGlobalGenerator()->AddRule(rule);
  337. }
  338. if (this->TargetNames.Output != this->TargetNames.Real &&
  339. !this->GetGeneratorTarget()->IsFrameworkOnApple()) {
  340. std::string cmakeCommand =
  341. this->GetLocalGenerator()->ConvertToOutputFormat(
  342. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  343. if (targetType == cmStateEnums::EXECUTABLE) {
  344. cmNinjaRule rule("CMAKE_SYMLINK_EXECUTABLE");
  345. {
  346. std::vector<std::string> cmd;
  347. cmd.push_back(cmakeCommand + " -E cmake_symlink_executable $in $out");
  348. cmd.emplace_back("$POST_BUILD");
  349. rule.Command = this->GetLocalGenerator()->BuildCommandLine(cmd);
  350. }
  351. rule.Description = "Creating executable symlink $out";
  352. rule.Comment = "Rule for creating executable symlink.";
  353. this->GetGlobalGenerator()->AddRule(rule);
  354. } else {
  355. cmNinjaRule rule("CMAKE_SYMLINK_LIBRARY");
  356. {
  357. std::vector<std::string> cmd;
  358. cmd.push_back(cmakeCommand +
  359. " -E cmake_symlink_library $in $SONAME $out");
  360. cmd.emplace_back("$POST_BUILD");
  361. rule.Command = this->GetLocalGenerator()->BuildCommandLine(cmd);
  362. }
  363. rule.Description = "Creating library symlink $out";
  364. rule.Comment = "Rule for creating library symlink.";
  365. this->GetGlobalGenerator()->AddRule(rule);
  366. }
  367. }
  368. }
  369. std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeDeviceLinkCmd()
  370. {
  371. std::vector<std::string> linkCmds;
  372. // this target requires separable cuda compilation
  373. // now build the correct command depending on if the target is
  374. // an executable or a dynamic library.
  375. std::string linkCmd;
  376. switch (this->GetGeneratorTarget()->GetType()) {
  377. case cmStateEnums::STATIC_LIBRARY:
  378. case cmStateEnums::SHARED_LIBRARY:
  379. case cmStateEnums::MODULE_LIBRARY: {
  380. const std::string cudaLinkCmd(
  381. this->GetMakefile()->GetDefinition("CMAKE_CUDA_DEVICE_LINK_LIBRARY"));
  382. cmExpandList(cudaLinkCmd, linkCmds);
  383. } break;
  384. case cmStateEnums::EXECUTABLE: {
  385. const std::string cudaLinkCmd(this->GetMakefile()->GetDefinition(
  386. "CMAKE_CUDA_DEVICE_LINK_EXECUTABLE"));
  387. cmExpandList(cudaLinkCmd, linkCmds);
  388. } break;
  389. default:
  390. break;
  391. }
  392. return linkCmds;
  393. }
  394. std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd()
  395. {
  396. std::vector<std::string> linkCmds;
  397. cmMakefile* mf = this->GetMakefile();
  398. {
  399. // If we have a rule variable prefer it. In the case of static libraries
  400. // this occurs when things like IPO is enabled, and we need to use the
  401. // CMAKE_<lang>_CREATE_STATIC_LIBRARY_IPO define instead.
  402. std::string linkCmdVar = this->GetGeneratorTarget()->GetCreateRuleVariable(
  403. this->TargetLinkLanguage, this->GetConfigName());
  404. const char* linkCmd = mf->GetDefinition(linkCmdVar);
  405. if (linkCmd) {
  406. std::string linkCmdStr = linkCmd;
  407. if (this->GetGeneratorTarget()->HasImplibGNUtoMS(this->ConfigName)) {
  408. std::string ruleVar = "CMAKE_";
  409. ruleVar += this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
  410. ruleVar += "_GNUtoMS_RULE";
  411. if (const char* rule = this->Makefile->GetDefinition(ruleVar)) {
  412. linkCmdStr += rule;
  413. }
  414. }
  415. cmExpandList(linkCmdStr, linkCmds);
  416. if (this->GetGeneratorTarget()->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
  417. std::string cmakeCommand =
  418. this->GetLocalGenerator()->ConvertToOutputFormat(
  419. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  420. cmakeCommand += " -E __run_co_compile --lwyu=";
  421. cmGeneratorTarget& gt = *this->GetGeneratorTarget();
  422. const std::string cfgName = this->GetConfigName();
  423. std::string targetOutputReal = this->ConvertToNinjaPath(
  424. gt.GetFullPath(cfgName, cmStateEnums::RuntimeBinaryArtifact,
  425. /*realname=*/true));
  426. cmakeCommand += targetOutputReal;
  427. linkCmds.push_back(std::move(cmakeCommand));
  428. }
  429. return linkCmds;
  430. }
  431. }
  432. switch (this->GetGeneratorTarget()->GetType()) {
  433. case cmStateEnums::STATIC_LIBRARY: {
  434. // We have archive link commands set. First, delete the existing archive.
  435. {
  436. std::string cmakeCommand =
  437. this->GetLocalGenerator()->ConvertToOutputFormat(
  438. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  439. linkCmds.push_back(cmakeCommand + " -E remove $TARGET_FILE");
  440. }
  441. // TODO: Use ARCHIVE_APPEND for archives over a certain size.
  442. {
  443. std::string linkCmdVar = "CMAKE_";
  444. linkCmdVar += this->TargetLinkLanguage;
  445. linkCmdVar += "_ARCHIVE_CREATE";
  446. linkCmdVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  447. linkCmdVar, this->TargetLinkLanguage, this->GetConfigName());
  448. std::string const& linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  449. cmExpandList(linkCmd, linkCmds);
  450. }
  451. {
  452. std::string linkCmdVar = "CMAKE_";
  453. linkCmdVar += this->TargetLinkLanguage;
  454. linkCmdVar += "_ARCHIVE_FINISH";
  455. linkCmdVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  456. linkCmdVar, this->TargetLinkLanguage, this->GetConfigName());
  457. std::string const& linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  458. cmExpandList(linkCmd, linkCmds);
  459. }
  460. #ifdef __APPLE__
  461. // On macOS ranlib truncates the fractional part of the static archive
  462. // file modification time. If the archive and at least one contained
  463. // object file were created within the same second this will make look
  464. // the archive older than the object file. On subsequent ninja runs this
  465. // leads to re-achiving and updating dependent targets.
  466. // As a work-around we touch the archive after ranlib (see #19222).
  467. {
  468. std::string cmakeCommand =
  469. this->GetLocalGenerator()->ConvertToOutputFormat(
  470. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  471. linkCmds.push_back(cmakeCommand + " -E touch $TARGET_FILE");
  472. }
  473. #endif
  474. return linkCmds;
  475. }
  476. case cmStateEnums::SHARED_LIBRARY:
  477. case cmStateEnums::MODULE_LIBRARY:
  478. case cmStateEnums::EXECUTABLE:
  479. break;
  480. default:
  481. assert(false && "Unexpected target type");
  482. }
  483. return std::vector<std::string>();
  484. }
  485. void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement()
  486. {
  487. cmGlobalNinjaGenerator* globalGen = this->GetGlobalGenerator();
  488. if (!globalGen->GetLanguageEnabled("CUDA")) {
  489. return;
  490. }
  491. cmGeneratorTarget* genTarget = this->GetGeneratorTarget();
  492. bool requiresDeviceLinking = requireDeviceLinking(
  493. *this->GeneratorTarget, *this->GetLocalGenerator(), this->ConfigName);
  494. if (!requiresDeviceLinking) {
  495. return;
  496. }
  497. // Now we can do device linking
  498. // First and very important step is to make sure while inside this
  499. // step our link language is set to CUDA
  500. std::string cudaLinkLanguage = "CUDA";
  501. std::string const& objExt =
  502. this->Makefile->GetSafeDefinition("CMAKE_CUDA_OUTPUT_EXTENSION");
  503. std::string const cfgName = this->GetConfigName();
  504. std::string const targetOutputReal = ConvertToNinjaPath(
  505. genTarget->ObjectDirectory + "cmake_device_link" + objExt);
  506. std::string const targetOutputImplib = ConvertToNinjaPath(
  507. genTarget->GetFullPath(cfgName, cmStateEnums::ImportLibraryArtifact));
  508. this->DeviceLinkObject = targetOutputReal;
  509. // Write comments.
  510. cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
  511. const cmStateEnums::TargetType targetType = genTarget->GetType();
  512. this->GetBuildFileStream() << "# Device Link build statements for "
  513. << cmState::GetTargetTypeName(targetType)
  514. << " target " << this->GetTargetName() << "\n\n";
  515. // Compute the comment.
  516. cmNinjaBuild build(this->LanguageLinkerDeviceRule());
  517. build.Comment = "Link the ";
  518. build.Comment += this->GetVisibleTypeName();
  519. build.Comment += " ";
  520. build.Comment += targetOutputReal;
  521. cmNinjaVars& vars = build.Variables;
  522. // Compute outputs.
  523. build.Outputs.push_back(targetOutputReal);
  524. // Compute specific libraries to link with.
  525. build.ExplicitDeps = this->GetObjects();
  526. build.ImplicitDeps = this->ComputeLinkDeps(this->TargetLinkLanguage);
  527. std::string frameworkPath;
  528. std::string linkPath;
  529. std::string createRule = genTarget->GetCreateRuleVariable(
  530. this->TargetLinkLanguage, this->GetConfigName());
  531. const bool useWatcomQuote =
  532. this->GetMakefile()->IsOn(createRule + "_USE_WATCOM_QUOTE");
  533. cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
  534. vars["TARGET_FILE"] =
  535. localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
  536. std::unique_ptr<cmLinkLineComputer> linkLineComputer(
  537. new cmNinjaLinkLineDeviceComputer(
  538. this->GetLocalGenerator(),
  539. this->GetLocalGenerator()->GetStateSnapshot().GetDirectory(),
  540. globalGen));
  541. linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
  542. localGen.GetTargetFlags(
  543. linkLineComputer.get(), this->GetConfigName(), vars["LINK_LIBRARIES"],
  544. vars["FLAGS"], vars["LINK_FLAGS"], frameworkPath, linkPath, genTarget);
  545. this->addPoolNinjaVariable("JOB_POOL_LINK", genTarget, vars);
  546. vars["LINK_FLAGS"] =
  547. cmGlobalNinjaGenerator::EncodeLiteral(vars["LINK_FLAGS"]);
  548. vars["MANIFESTS"] = this->GetManifests();
  549. vars["LINK_PATH"] = frameworkPath + linkPath;
  550. // Compute architecture specific link flags. Yes, these go into a different
  551. // variable for executables, probably due to a mistake made when duplicating
  552. // code between the Makefile executable and library generators.
  553. if (targetType == cmStateEnums::EXECUTABLE) {
  554. std::string t = vars["FLAGS"];
  555. localGen.AddArchitectureFlags(t, genTarget, cudaLinkLanguage, cfgName);
  556. vars["FLAGS"] = t;
  557. } else {
  558. std::string t = vars["ARCH_FLAGS"];
  559. localGen.AddArchitectureFlags(t, genTarget, cudaLinkLanguage, cfgName);
  560. vars["ARCH_FLAGS"] = t;
  561. t.clear();
  562. localGen.AddLanguageFlagsForLinking(t, genTarget, cudaLinkLanguage,
  563. cfgName);
  564. vars["LANGUAGE_COMPILE_FLAGS"] = t;
  565. }
  566. if (genTarget->HasSOName(cfgName)) {
  567. vars["SONAME_FLAG"] =
  568. this->GetMakefile()->GetSONameFlag(this->TargetLinkLanguage);
  569. vars["SONAME"] = this->TargetNames.SharedObject;
  570. if (targetType == cmStateEnums::SHARED_LIBRARY) {
  571. std::string install_dir =
  572. this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(cfgName);
  573. if (!install_dir.empty()) {
  574. vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
  575. install_dir, cmOutputConverter::SHELL);
  576. }
  577. }
  578. }
  579. if (!this->TargetNames.ImportLibrary.empty()) {
  580. const std::string impLibPath = localGen.ConvertToOutputFormat(
  581. targetOutputImplib, cmOutputConverter::SHELL);
  582. vars["TARGET_IMPLIB"] = impLibPath;
  583. EnsureParentDirectoryExists(impLibPath);
  584. }
  585. const std::string objPath = GetGeneratorTarget()->GetSupportDirectory();
  586. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  587. this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
  588. EnsureDirectoryExists(objPath);
  589. this->SetMsvcTargetPdbVariable(vars);
  590. if (globalGen->IsGCCOnWindows()) {
  591. // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
  592. std::string& linkLibraries = vars["LINK_LIBRARIES"];
  593. std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
  594. std::string& link_path = vars["LINK_PATH"];
  595. std::replace(link_path.begin(), link_path.end(), '\\', '/');
  596. }
  597. // Device linking currently doesn't support response files so
  598. // do not check if the user has explicitly forced a response file.
  599. int const commandLineLengthLimit =
  600. static_cast<int>(cmSystemTools::CalculateCommandLineLengthLimit()) -
  601. globalGen->GetRuleCmdLength(this->LanguageLinkerDeviceRule());
  602. build.RspFile = this->ConvertToNinjaPath(std::string("CMakeFiles/") +
  603. genTarget->GetName() + ".rsp");
  604. // Gather order-only dependencies.
  605. this->GetLocalGenerator()->AppendTargetDepends(this->GetGeneratorTarget(),
  606. build.OrderOnlyDeps);
  607. // Write the build statement for this target.
  608. bool usedResponseFile = false;
  609. globalGen->WriteBuild(this->GetBuildFileStream(), build,
  610. commandLineLengthLimit, &usedResponseFile);
  611. this->WriteDeviceLinkRule(usedResponseFile);
  612. }
  613. void cmNinjaNormalTargetGenerator::WriteLinkStatement()
  614. {
  615. cmMakefile* mf = this->GetMakefile();
  616. cmGlobalNinjaGenerator* globalGen = this->GetGlobalGenerator();
  617. cmGeneratorTarget* gt = this->GetGeneratorTarget();
  618. const std::string cfgName = this->GetConfigName();
  619. std::string targetOutput = ConvertToNinjaPath(gt->GetFullPath(cfgName));
  620. std::string targetOutputReal = ConvertToNinjaPath(
  621. gt->GetFullPath(cfgName, cmStateEnums::RuntimeBinaryArtifact,
  622. /*realname=*/true));
  623. std::string targetOutputImplib = ConvertToNinjaPath(
  624. gt->GetFullPath(cfgName, cmStateEnums::ImportLibraryArtifact));
  625. if (gt->IsAppBundleOnApple()) {
  626. // Create the app bundle
  627. std::string outpath = gt->GetDirectory(cfgName);
  628. this->OSXBundleGenerator->CreateAppBundle(this->TargetNames.Output,
  629. outpath);
  630. // Calculate the output path
  631. targetOutput = outpath;
  632. targetOutput += "/";
  633. targetOutput += this->TargetNames.Output;
  634. targetOutput = this->ConvertToNinjaPath(targetOutput);
  635. targetOutputReal = outpath;
  636. targetOutputReal += "/";
  637. targetOutputReal += this->TargetNames.Real;
  638. targetOutputReal = this->ConvertToNinjaPath(targetOutputReal);
  639. } else if (gt->IsFrameworkOnApple()) {
  640. // Create the library framework.
  641. this->OSXBundleGenerator->CreateFramework(this->TargetNames.Output,
  642. gt->GetDirectory(cfgName));
  643. } else if (gt->IsCFBundleOnApple()) {
  644. // Create the core foundation bundle.
  645. this->OSXBundleGenerator->CreateCFBundle(this->TargetNames.Output,
  646. gt->GetDirectory(cfgName));
  647. }
  648. // Write comments.
  649. cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
  650. const cmStateEnums::TargetType targetType = gt->GetType();
  651. this->GetBuildFileStream()
  652. << "# Link build statements for " << cmState::GetTargetTypeName(targetType)
  653. << " target " << this->GetTargetName() << "\n\n";
  654. cmNinjaBuild linkBuild(this->LanguageLinkerRule());
  655. cmNinjaVars& vars = linkBuild.Variables;
  656. // Compute the comment.
  657. linkBuild.Comment = "Link the ";
  658. linkBuild.Comment += this->GetVisibleTypeName();
  659. linkBuild.Comment += " ";
  660. linkBuild.Comment += targetOutputReal;
  661. // Compute outputs.
  662. linkBuild.Outputs.push_back(targetOutputReal);
  663. if (this->TargetLinkLanguage == "Swift") {
  664. vars["SWIFT_LIBRARY_NAME"] = [this]() -> std::string {
  665. cmGeneratorTarget::Names targetNames =
  666. this->GetGeneratorTarget()->GetLibraryNames(this->GetConfigName());
  667. return targetNames.Base;
  668. }();
  669. vars["SWIFT_MODULE_NAME"] = [gt]() -> std::string {
  670. if (const char* name = gt->GetProperty("Swift_MODULE_NAME")) {
  671. return name;
  672. }
  673. return gt->GetName();
  674. }();
  675. vars["SWIFT_MODULE"] = [this](const std::string& module) -> std::string {
  676. std::string directory =
  677. this->GetLocalGenerator()->GetCurrentBinaryDirectory();
  678. if (const char* prop = this->GetGeneratorTarget()->GetProperty(
  679. "Swift_MODULE_DIRECTORY")) {
  680. directory = prop;
  681. }
  682. std::string name = module + ".swiftmodule";
  683. if (const char* prop =
  684. this->GetGeneratorTarget()->GetProperty("Swift_MODULE")) {
  685. name = prop;
  686. }
  687. return this->GetLocalGenerator()->ConvertToOutputFormat(
  688. this->ConvertToNinjaPath(directory + "/" + name),
  689. cmOutputConverter::SHELL);
  690. }(vars["SWIFT_MODULE_NAME"]);
  691. vars["SWIFT_OUTPUT_FILE_MAP"] =
  692. this->GetLocalGenerator()->ConvertToOutputFormat(
  693. this->ConvertToNinjaPath(gt->GetSupportDirectory() +
  694. "/output-file-map.json"),
  695. cmOutputConverter::SHELL);
  696. vars["SWIFT_SOURCES"] = [this]() -> std::string {
  697. std::vector<cmSourceFile const*> sources;
  698. std::stringstream oss;
  699. this->GetGeneratorTarget()->GetObjectSources(sources,
  700. this->GetConfigName());
  701. cmLocalGenerator const* LocalGen = this->GetLocalGenerator();
  702. for (const auto& source : sources) {
  703. oss << " "
  704. << LocalGen->ConvertToOutputFormat(
  705. this->ConvertToNinjaPath(this->GetSourceFilePath(source)),
  706. cmOutputConverter::SHELL);
  707. }
  708. return oss.str();
  709. }();
  710. // Since we do not perform object builds, compute the
  711. // defines/flags/includes here so that they can be passed along
  712. // appropriately.
  713. vars["DEFINES"] = this->GetDefines("Swift");
  714. vars["FLAGS"] = this->GetFlags("Swift");
  715. vars["INCLUDES"] = this->GetIncludes("Swift");
  716. }
  717. // Compute specific libraries to link with.
  718. if (this->TargetLinkLanguage == "Swift") {
  719. std::vector<cmSourceFile const*> sources;
  720. gt->GetObjectSources(sources, this->GetConfigName());
  721. for (const auto& source : sources) {
  722. linkBuild.Outputs.push_back(
  723. this->ConvertToNinjaPath(this->GetObjectFilePath(source)));
  724. linkBuild.ExplicitDeps.push_back(
  725. this->ConvertToNinjaPath(this->GetSourceFilePath(source)));
  726. }
  727. linkBuild.Outputs.push_back(vars["SWIFT_MODULE"]);
  728. } else {
  729. linkBuild.ExplicitDeps = this->GetObjects();
  730. }
  731. linkBuild.ImplicitDeps = this->ComputeLinkDeps(this->TargetLinkLanguage);
  732. if (!this->DeviceLinkObject.empty()) {
  733. linkBuild.ExplicitDeps.push_back(this->DeviceLinkObject);
  734. }
  735. std::string frameworkPath;
  736. std::string linkPath;
  737. std::string createRule =
  738. gt->GetCreateRuleVariable(this->TargetLinkLanguage, this->GetConfigName());
  739. bool useWatcomQuote = mf->IsOn(createRule + "_USE_WATCOM_QUOTE");
  740. cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
  741. vars["TARGET_FILE"] =
  742. localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
  743. std::unique_ptr<cmLinkLineComputer> linkLineComputer(
  744. globalGen->CreateLinkLineComputer(
  745. this->GetLocalGenerator(),
  746. this->GetLocalGenerator()->GetStateSnapshot().GetDirectory()));
  747. linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
  748. localGen.GetTargetFlags(linkLineComputer.get(), this->GetConfigName(),
  749. vars["LINK_LIBRARIES"], vars["FLAGS"],
  750. vars["LINK_FLAGS"], frameworkPath, linkPath, gt);
  751. // Add OS X version flags, if any.
  752. if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  753. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  754. this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
  755. "COMPATIBILITY", true);
  756. this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
  757. "CURRENT", false);
  758. }
  759. this->addPoolNinjaVariable("JOB_POOL_LINK", gt, vars);
  760. this->AddModuleDefinitionFlag(linkLineComputer.get(), vars["LINK_FLAGS"]);
  761. vars["LINK_FLAGS"] =
  762. cmGlobalNinjaGenerator::EncodeLiteral(vars["LINK_FLAGS"]);
  763. vars["MANIFESTS"] = this->GetManifests();
  764. vars["LINK_PATH"] = frameworkPath + linkPath;
  765. std::string lwyuFlags;
  766. if (gt->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
  767. lwyuFlags = " -Wl,--no-as-needed";
  768. }
  769. // Compute architecture specific link flags. Yes, these go into a different
  770. // variable for executables, probably due to a mistake made when duplicating
  771. // code between the Makefile executable and library generators.
  772. if (targetType == cmStateEnums::EXECUTABLE) {
  773. std::string t = vars["FLAGS"];
  774. localGen.AddArchitectureFlags(t, gt, TargetLinkLanguage, cfgName);
  775. t += lwyuFlags;
  776. vars["FLAGS"] = t;
  777. } else {
  778. std::string t = vars["ARCH_FLAGS"];
  779. localGen.AddArchitectureFlags(t, gt, TargetLinkLanguage, cfgName);
  780. vars["ARCH_FLAGS"] = t;
  781. t.clear();
  782. t += lwyuFlags;
  783. localGen.AddLanguageFlagsForLinking(t, gt, TargetLinkLanguage, cfgName);
  784. vars["LANGUAGE_COMPILE_FLAGS"] = t;
  785. }
  786. if (gt->HasSOName(cfgName)) {
  787. vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage);
  788. vars["SONAME"] = this->TargetNames.SharedObject;
  789. if (targetType == cmStateEnums::SHARED_LIBRARY) {
  790. std::string install_dir = gt->GetInstallNameDirForBuildTree(cfgName);
  791. if (!install_dir.empty()) {
  792. vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
  793. install_dir, cmOutputConverter::SHELL);
  794. }
  795. }
  796. }
  797. cmNinjaDeps byproducts;
  798. if (!this->TargetNames.ImportLibrary.empty()) {
  799. const std::string impLibPath = localGen.ConvertToOutputFormat(
  800. targetOutputImplib, cmOutputConverter::SHELL);
  801. vars["TARGET_IMPLIB"] = impLibPath;
  802. EnsureParentDirectoryExists(impLibPath);
  803. if (gt->HasImportLibrary(cfgName)) {
  804. byproducts.push_back(targetOutputImplib);
  805. }
  806. }
  807. if (!this->SetMsvcTargetPdbVariable(vars)) {
  808. // It is common to place debug symbols at a specific place,
  809. // so we need a plain target name in the rule available.
  810. std::string prefix;
  811. std::string base;
  812. std::string suffix;
  813. gt->GetFullNameComponents(prefix, base, suffix);
  814. std::string dbg_suffix = ".dbg";
  815. // TODO: Where to document?
  816. if (mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX")) {
  817. dbg_suffix = mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX");
  818. }
  819. vars["TARGET_PDB"] = base + suffix + dbg_suffix;
  820. }
  821. const std::string objPath = gt->GetSupportDirectory();
  822. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  823. this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
  824. EnsureDirectoryExists(objPath);
  825. if (globalGen->IsGCCOnWindows()) {
  826. // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
  827. std::string& linkLibraries = vars["LINK_LIBRARIES"];
  828. std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
  829. std::string& link_path = vars["LINK_PATH"];
  830. std::replace(link_path.begin(), link_path.end(), '\\', '/');
  831. }
  832. const std::vector<cmCustomCommand>* cmdLists[3] = {
  833. &gt->GetPreBuildCommands(), &gt->GetPreLinkCommands(),
  834. &gt->GetPostBuildCommands()
  835. };
  836. std::vector<std::string> preLinkCmdLines, postBuildCmdLines;
  837. std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines,
  838. &preLinkCmdLines,
  839. &postBuildCmdLines };
  840. for (unsigned i = 0; i != 3; ++i) {
  841. for (cmCustomCommand const& cc : *cmdLists[i]) {
  842. cmCustomCommandGenerator ccg(cc, cfgName, this->GetLocalGenerator());
  843. localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
  844. std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
  845. std::transform(ccByproducts.begin(), ccByproducts.end(),
  846. std::back_inserter(byproducts), MapToNinjaPath());
  847. }
  848. }
  849. // maybe create .def file from list of objects
  850. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  851. gt->GetModuleDefinitionInfo(this->GetConfigName());
  852. if (mdi && mdi->DefFileGenerated) {
  853. std::string cmakeCommand =
  854. this->GetLocalGenerator()->ConvertToOutputFormat(
  855. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  856. std::string cmd = cmakeCommand;
  857. cmd += " -E __create_def ";
  858. cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
  859. mdi->DefFile, cmOutputConverter::SHELL);
  860. cmd += " ";
  861. std::string obj_list_file = mdi->DefFile + ".objs";
  862. cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
  863. obj_list_file, cmOutputConverter::SHELL);
  864. preLinkCmdLines.push_back(std::move(cmd));
  865. // create a list of obj files for the -E __create_def to read
  866. cmGeneratedFileStream fout(obj_list_file);
  867. if (mdi->WindowsExportAllSymbols) {
  868. cmNinjaDeps objs = this->GetObjects();
  869. for (std::string const& obj : objs) {
  870. if (cmHasLiteralSuffix(obj, ".obj")) {
  871. fout << obj << "\n";
  872. }
  873. }
  874. }
  875. for (cmSourceFile const* src : mdi->Sources) {
  876. fout << src->GetFullPath() << "\n";
  877. }
  878. }
  879. // If we have any PRE_LINK commands, we need to go back to CMAKE_BINARY_DIR
  880. // for the link commands.
  881. if (!preLinkCmdLines.empty()) {
  882. const std::string homeOutDir = localGen.ConvertToOutputFormat(
  883. localGen.GetBinaryDirectory(), cmOutputConverter::SHELL);
  884. preLinkCmdLines.push_back("cd " + homeOutDir);
  885. }
  886. vars["PRE_LINK"] = localGen.BuildCommandLine(preLinkCmdLines, "pre-link",
  887. this->GeneratorTarget);
  888. std::string postBuildCmdLine = localGen.BuildCommandLine(
  889. postBuildCmdLines, "post-build", this->GeneratorTarget);
  890. cmNinjaVars symlinkVars;
  891. bool const symlinkNeeded =
  892. (targetOutput != targetOutputReal && !gt->IsFrameworkOnApple());
  893. if (!symlinkNeeded) {
  894. vars["POST_BUILD"] = postBuildCmdLine;
  895. } else {
  896. vars["POST_BUILD"] = cmGlobalNinjaGenerator::SHELL_NOOP;
  897. symlinkVars["POST_BUILD"] = postBuildCmdLine;
  898. }
  899. std::string cmakeVarLang = "CMAKE_";
  900. cmakeVarLang += this->TargetLinkLanguage;
  901. // build response file name
  902. std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
  903. const char* flag = GetMakefile()->GetDefinition(cmakeLinkVar);
  904. bool const lang_supports_response =
  905. !(this->TargetLinkLanguage == "RC" ||
  906. (this->TargetLinkLanguage == "CUDA" && !flag));
  907. int commandLineLengthLimit = -1;
  908. if (!lang_supports_response || !this->ForceResponseFile()) {
  909. commandLineLengthLimit =
  910. static_cast<int>(cmSystemTools::CalculateCommandLineLengthLimit()) -
  911. globalGen->GetRuleCmdLength(linkBuild.Rule);
  912. }
  913. linkBuild.RspFile = this->ConvertToNinjaPath(std::string("CMakeFiles/") +
  914. gt->GetName() + ".rsp");
  915. // Gather order-only dependencies.
  916. this->GetLocalGenerator()->AppendTargetDepends(gt, linkBuild.OrderOnlyDeps);
  917. // Ninja should restat after linking if and only if there are byproducts.
  918. vars["RESTAT"] = byproducts.empty() ? "" : "1";
  919. for (std::string const& o : byproducts) {
  920. globalGen->SeenCustomCommandOutput(o);
  921. linkBuild.Outputs.push_back(o);
  922. }
  923. // Write the build statement for this target.
  924. bool usedResponseFile = false;
  925. globalGen->WriteBuild(this->GetBuildFileStream(), linkBuild,
  926. commandLineLengthLimit, &usedResponseFile);
  927. this->WriteLinkRule(usedResponseFile);
  928. if (symlinkNeeded) {
  929. if (targetType == cmStateEnums::EXECUTABLE) {
  930. cmNinjaBuild build("CMAKE_SYMLINK_EXECUTABLE");
  931. build.Comment = "Create executable symlink " + targetOutput;
  932. build.Outputs.push_back(targetOutput);
  933. build.ExplicitDeps.push_back(targetOutputReal);
  934. build.Variables = std::move(symlinkVars);
  935. globalGen->WriteBuild(this->GetBuildFileStream(), build);
  936. } else {
  937. cmNinjaBuild build("CMAKE_SYMLINK_LIBRARY");
  938. build.Comment = "Create library symlink " + targetOutput;
  939. std::string const soName = this->ConvertToNinjaPath(
  940. this->GetTargetFilePath(this->TargetNames.SharedObject));
  941. // If one link has to be created.
  942. if (targetOutputReal == soName || targetOutput == soName) {
  943. symlinkVars["SONAME"] =
  944. this->GetLocalGenerator()->ConvertToOutputFormat(
  945. soName, cmOutputConverter::SHELL);
  946. } else {
  947. symlinkVars["SONAME"].clear();
  948. build.Outputs.push_back(soName);
  949. }
  950. build.Outputs.push_back(targetOutput);
  951. build.ExplicitDeps.push_back(targetOutputReal);
  952. build.Variables = std::move(symlinkVars);
  953. globalGen->WriteBuild(this->GetBuildFileStream(), build);
  954. }
  955. }
  956. // Add aliases for the file name and the target name.
  957. globalGen->AddTargetAlias(this->TargetNames.Output, gt);
  958. globalGen->AddTargetAlias(this->GetTargetName(), gt);
  959. }
  960. void cmNinjaNormalTargetGenerator::WriteObjectLibStatement()
  961. {
  962. // Write a phony output that depends on all object files.
  963. {
  964. cmNinjaBuild build("phony");
  965. build.Comment = "Object library " + this->GetTargetName();
  966. this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
  967. build.Outputs);
  968. build.ExplicitDeps = this->GetObjects();
  969. this->GetGlobalGenerator()->WriteBuild(this->GetBuildFileStream(), build);
  970. }
  971. // Add aliases for the target name.
  972. this->GetGlobalGenerator()->AddTargetAlias(this->GetTargetName(),
  973. this->GetGeneratorTarget());
  974. }