1
0

cmNinjaNormalTargetGenerator.cxx 41 KB

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