cmNinjaNormalTargetGenerator.cxx 41 KB

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