cmNinjaNormalTargetGenerator.cxx 41 KB

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