cmMakefileLibraryTargetGenerator.cxx 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  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 "cmMakefileLibraryTargetGenerator.h"
  4. #include <set>
  5. #include <sstream>
  6. #include <stddef.h>
  7. #include <utility>
  8. #include <vector>
  9. #include "cm_memory.hxx"
  10. #include "cmAlgorithms.h"
  11. #include "cmGeneratedFileStream.h"
  12. #include "cmGeneratorTarget.h"
  13. #include "cmGlobalUnixMakefileGenerator3.h"
  14. #include "cmLinkLineComputer.h"
  15. #include "cmLinkLineDeviceComputer.h"
  16. #include "cmLocalGenerator.h"
  17. #include "cmLocalUnixMakefileGenerator3.h"
  18. #include "cmMakefile.h"
  19. #include "cmOSXBundleGenerator.h"
  20. #include "cmOutputConverter.h"
  21. #include "cmRulePlaceholderExpander.h"
  22. #include "cmState.h"
  23. #include "cmStateDirectory.h"
  24. #include "cmStateSnapshot.h"
  25. #include "cmStateTypes.h"
  26. #include "cmStringAlgorithms.h"
  27. #include "cmSystemTools.h"
  28. cmMakefileLibraryTargetGenerator::cmMakefileLibraryTargetGenerator(
  29. cmGeneratorTarget* target)
  30. : cmMakefileTargetGenerator(target)
  31. {
  32. this->CustomCommandDriver = OnDepends;
  33. if (this->GeneratorTarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  34. this->TargetNames =
  35. this->GeneratorTarget->GetLibraryNames(this->ConfigName);
  36. }
  37. this->OSXBundleGenerator =
  38. cm::make_unique<cmOSXBundleGenerator>(target, this->ConfigName);
  39. this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders);
  40. this->LocalGenerator->AddPchDependencies(target, this->ConfigName);
  41. }
  42. cmMakefileLibraryTargetGenerator::~cmMakefileLibraryTargetGenerator() =
  43. default;
  44. void cmMakefileLibraryTargetGenerator::WriteRuleFiles()
  45. {
  46. // create the build.make file and directory, put in the common blocks
  47. this->CreateRuleFile();
  48. // write rules used to help build object files
  49. this->WriteCommonCodeRules();
  50. // write the per-target per-language flags
  51. this->WriteTargetLanguageFlags();
  52. // write in rules for object files and custom commands
  53. this->WriteTargetBuildRules();
  54. // write the link rules
  55. // Write the rule for this target type.
  56. switch (this->GeneratorTarget->GetType()) {
  57. case cmStateEnums::STATIC_LIBRARY:
  58. this->WriteStaticLibraryRules();
  59. break;
  60. case cmStateEnums::SHARED_LIBRARY:
  61. this->WriteSharedLibraryRules(false);
  62. if (this->GeneratorTarget->NeedRelinkBeforeInstall(this->ConfigName)) {
  63. // Write rules to link an installable version of the target.
  64. this->WriteSharedLibraryRules(true);
  65. }
  66. break;
  67. case cmStateEnums::MODULE_LIBRARY:
  68. this->WriteModuleLibraryRules(false);
  69. if (this->GeneratorTarget->NeedRelinkBeforeInstall(this->ConfigName)) {
  70. // Write rules to link an installable version of the target.
  71. this->WriteModuleLibraryRules(true);
  72. }
  73. break;
  74. case cmStateEnums::OBJECT_LIBRARY:
  75. this->WriteObjectLibraryRules();
  76. break;
  77. default:
  78. // If language is not known, this is an error.
  79. cmSystemTools::Error("Unknown Library Type");
  80. break;
  81. }
  82. // Write clean target
  83. this->WriteTargetCleanRules();
  84. // Write the dependency generation rule. This must be done last so
  85. // that multiple output pair information is available.
  86. this->WriteTargetDependRules();
  87. // close the streams
  88. this->CloseFileStreams();
  89. }
  90. void cmMakefileLibraryTargetGenerator::WriteObjectLibraryRules()
  91. {
  92. std::vector<std::string> commands;
  93. std::vector<std::string> depends;
  94. // Add post-build rules.
  95. this->LocalGenerator->AppendCustomCommands(
  96. commands, this->GeneratorTarget->GetPostBuildCommands(),
  97. this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
  98. // Depend on the object files.
  99. this->AppendObjectDepends(depends);
  100. // Write the rule.
  101. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  102. this->GeneratorTarget->GetName(),
  103. depends, commands, true);
  104. // Write the main driver rule to build everything in this target.
  105. this->WriteTargetDriverRule(this->GeneratorTarget->GetName(), false);
  106. }
  107. void cmMakefileLibraryTargetGenerator::WriteStaticLibraryRules()
  108. {
  109. const bool requiresDeviceLinking = requireDeviceLinking(
  110. *this->GeneratorTarget, *this->LocalGenerator, this->ConfigName);
  111. if (requiresDeviceLinking) {
  112. std::string linkRuleVar = "CMAKE_CUDA_DEVICE_LINK_LIBRARY";
  113. this->WriteDeviceLibraryRules(linkRuleVar, false);
  114. }
  115. std::string linkLanguage =
  116. this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
  117. std::string linkRuleVar = this->GeneratorTarget->GetCreateRuleVariable(
  118. linkLanguage, this->ConfigName);
  119. std::string extraFlags;
  120. this->LocalGenerator->GetStaticLibraryFlags(
  121. extraFlags, cmSystemTools::UpperCase(this->ConfigName), linkLanguage,
  122. this->GeneratorTarget);
  123. this->WriteLibraryRules(linkRuleVar, extraFlags, false);
  124. }
  125. void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink)
  126. {
  127. if (this->GeneratorTarget->IsFrameworkOnApple()) {
  128. this->WriteFrameworkRules(relink);
  129. return;
  130. }
  131. if (!relink) {
  132. const bool requiresDeviceLinking = requireDeviceLinking(
  133. *this->GeneratorTarget, *this->LocalGenerator, this->ConfigName);
  134. if (requiresDeviceLinking) {
  135. std::string linkRuleVar = "CMAKE_CUDA_DEVICE_LINK_LIBRARY";
  136. this->WriteDeviceLibraryRules(linkRuleVar, relink);
  137. }
  138. }
  139. std::string linkLanguage =
  140. this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
  141. std::string linkRuleVar =
  142. cmStrCat("CMAKE_", linkLanguage, "_CREATE_SHARED_LIBRARY");
  143. std::string extraFlags;
  144. this->GetTargetLinkFlags(extraFlags, linkLanguage);
  145. this->LocalGenerator->AddConfigVariableFlags(
  146. extraFlags, "CMAKE_SHARED_LINKER_FLAGS", this->ConfigName);
  147. std::unique_ptr<cmLinkLineComputer> linkLineComputer(
  148. this->CreateLinkLineComputer(
  149. this->LocalGenerator,
  150. this->LocalGenerator->GetStateSnapshot().GetDirectory()));
  151. this->AddModuleDefinitionFlag(linkLineComputer.get(), extraFlags);
  152. if (this->GeneratorTarget->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
  153. this->LocalGenerator->AppendFlags(extraFlags, " -Wl,--no-as-needed");
  154. }
  155. this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
  156. }
  157. void cmMakefileLibraryTargetGenerator::WriteModuleLibraryRules(bool relink)
  158. {
  159. if (!relink) {
  160. const bool requiresDeviceLinking = requireDeviceLinking(
  161. *this->GeneratorTarget, *this->LocalGenerator, this->ConfigName);
  162. if (requiresDeviceLinking) {
  163. std::string linkRuleVar = "CMAKE_CUDA_DEVICE_LINK_LIBRARY";
  164. this->WriteDeviceLibraryRules(linkRuleVar, relink);
  165. }
  166. }
  167. std::string linkLanguage =
  168. this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
  169. std::string linkRuleVar =
  170. cmStrCat("CMAKE_", linkLanguage, "_CREATE_SHARED_MODULE");
  171. std::string extraFlags;
  172. this->GetTargetLinkFlags(extraFlags, linkLanguage);
  173. this->LocalGenerator->AddConfigVariableFlags(
  174. extraFlags, "CMAKE_MODULE_LINKER_FLAGS", this->ConfigName);
  175. std::unique_ptr<cmLinkLineComputer> linkLineComputer(
  176. this->CreateLinkLineComputer(
  177. this->LocalGenerator,
  178. this->LocalGenerator->GetStateSnapshot().GetDirectory()));
  179. this->AddModuleDefinitionFlag(linkLineComputer.get(), extraFlags);
  180. this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
  181. }
  182. void cmMakefileLibraryTargetGenerator::WriteFrameworkRules(bool relink)
  183. {
  184. std::string linkLanguage =
  185. this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
  186. std::string linkRuleVar =
  187. cmStrCat("CMAKE_", linkLanguage, "_CREATE_MACOSX_FRAMEWORK");
  188. std::string extraFlags;
  189. this->GetTargetLinkFlags(extraFlags, linkLanguage);
  190. this->LocalGenerator->AddConfigVariableFlags(
  191. extraFlags, "CMAKE_MACOSX_FRAMEWORK_LINKER_FLAGS", this->ConfigName);
  192. this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
  193. }
  194. void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules(
  195. const std::string& linkRuleVar, bool relink)
  196. {
  197. #ifndef CMAKE_BOOTSTRAP
  198. // TODO: Merge the methods that call this method to avoid
  199. // code duplication.
  200. std::vector<std::string> commands;
  201. // Get the language to use for linking this library.
  202. std::string linkLanguage = "CUDA";
  203. std::string const objExt =
  204. this->Makefile->GetSafeDefinition("CMAKE_CUDA_OUTPUT_EXTENSION");
  205. // Build list of dependencies.
  206. std::vector<std::string> depends;
  207. this->AppendLinkDepends(depends, linkLanguage);
  208. // Create set of linking flags.
  209. std::string linkFlags;
  210. this->GetTargetLinkFlags(linkFlags, linkLanguage);
  211. // Get the name of the device object to generate.
  212. std::string const targetOutputReal =
  213. this->GeneratorTarget->ObjectDirectory + "cmake_device_link" + objExt;
  214. this->DeviceLinkObject = targetOutputReal;
  215. this->NumberOfProgressActions++;
  216. if (!this->NoRuleMessages) {
  217. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  218. this->MakeEchoProgress(progress);
  219. // Add the link message.
  220. std::string buildEcho =
  221. cmStrCat("Linking ", linkLanguage, " device code ",
  222. this->LocalGenerator->ConvertToOutputFormat(
  223. this->LocalGenerator->MaybeConvertToRelativePath(
  224. this->LocalGenerator->GetCurrentBinaryDirectory(),
  225. this->DeviceLinkObject),
  226. cmOutputConverter::SHELL));
  227. this->LocalGenerator->AppendEcho(
  228. commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
  229. }
  230. // Clean files associated with this library.
  231. std::set<std::string> libCleanFiles;
  232. libCleanFiles.insert(this->LocalGenerator->MaybeConvertToRelativePath(
  233. this->LocalGenerator->GetCurrentBinaryDirectory(), targetOutputReal));
  234. // Determine whether a link script will be used.
  235. bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
  236. bool useResponseFileForObjects =
  237. this->CheckUseResponseFileForObjects(linkLanguage);
  238. bool const useResponseFileForLibs =
  239. this->CheckUseResponseFileForLibraries(linkLanguage);
  240. cmRulePlaceholderExpander::RuleVariables vars;
  241. vars.Language = linkLanguage.c_str();
  242. // Expand the rule variables.
  243. std::vector<std::string> real_link_commands;
  244. {
  245. bool useWatcomQuote =
  246. this->Makefile->IsOn(linkRuleVar + "_USE_WATCOM_QUOTE");
  247. // Set path conversion for link script shells.
  248. this->LocalGenerator->SetLinkScriptShell(useLinkScript);
  249. // Collect up flags to link in needed libraries.
  250. std::string linkLibs;
  251. if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
  252. std::unique_ptr<cmLinkLineComputer> linkLineComputer(
  253. new cmLinkLineDeviceComputer(
  254. this->LocalGenerator,
  255. this->LocalGenerator->GetStateSnapshot().GetDirectory()));
  256. linkLineComputer->SetForResponse(useResponseFileForLibs);
  257. linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
  258. linkLineComputer->SetRelink(relink);
  259. this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
  260. useResponseFileForLibs, depends);
  261. }
  262. // Construct object file lists that may be needed to expand the
  263. // rule.
  264. std::string buildObjs;
  265. this->CreateObjectLists(useLinkScript, false, // useArchiveRules
  266. useResponseFileForObjects, buildObjs, depends,
  267. useWatcomQuote);
  268. cmOutputConverter::OutputFormat output = (useWatcomQuote)
  269. ? cmOutputConverter::WATCOMQUOTE
  270. : cmOutputConverter::SHELL;
  271. std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
  272. objectDir = this->LocalGenerator->ConvertToOutputFormat(
  273. this->LocalGenerator->MaybeConvertToRelativePath(
  274. this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
  275. cmOutputConverter::SHELL);
  276. std::string target = this->LocalGenerator->ConvertToOutputFormat(
  277. this->LocalGenerator->MaybeConvertToRelativePath(
  278. this->LocalGenerator->GetCurrentBinaryDirectory(), targetOutputReal),
  279. output);
  280. std::string targetFullPathCompilePDB = this->ComputeTargetCompilePDB();
  281. std::string targetOutPathCompilePDB =
  282. this->LocalGenerator->ConvertToOutputFormat(targetFullPathCompilePDB,
  283. cmOutputConverter::SHELL);
  284. vars.Objects = buildObjs.c_str();
  285. vars.ObjectDir = objectDir.c_str();
  286. vars.Target = target.c_str();
  287. vars.LinkLibraries = linkLibs.c_str();
  288. vars.ObjectsQuoted = buildObjs.c_str();
  289. vars.LinkFlags = linkFlags.c_str();
  290. vars.TargetCompilePDB = targetOutPathCompilePDB.c_str();
  291. // Add language-specific flags.
  292. std::string langFlags;
  293. this->LocalGenerator->AddLanguageFlagsForLinking(
  294. langFlags, this->GeneratorTarget, linkLanguage, this->ConfigName);
  295. vars.LanguageCompileFlags = langFlags.c_str();
  296. std::string launcher;
  297. const char* val = this->LocalGenerator->GetRuleLauncher(
  298. this->GeneratorTarget, "RULE_LAUNCH_LINK");
  299. if (val && *val) {
  300. launcher = cmStrCat(val, ' ');
  301. }
  302. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  303. this->LocalGenerator->CreateRulePlaceholderExpander());
  304. // Construct the main link rule and expand placeholders.
  305. rulePlaceholderExpander->SetTargetImpLib(targetOutputReal);
  306. std::string linkRule = this->GetLinkRule(linkRuleVar);
  307. cmExpandList(linkRule, real_link_commands);
  308. // Expand placeholders.
  309. for (std::string& real_link_command : real_link_commands) {
  310. real_link_command = cmStrCat(launcher, real_link_command);
  311. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  312. real_link_command, vars);
  313. }
  314. // Restore path conversion to normal shells.
  315. this->LocalGenerator->SetLinkScriptShell(false);
  316. // Clean all the possible library names and symlinks.
  317. this->CleanFiles.insert(libCleanFiles.begin(), libCleanFiles.end());
  318. }
  319. std::vector<std::string> commands1;
  320. // Optionally convert the build rule to use a script to avoid long
  321. // command lines in the make shell.
  322. if (useLinkScript) {
  323. // Use a link script.
  324. const char* name = (relink ? "drelink.txt" : "dlink.txt");
  325. this->CreateLinkScript(name, real_link_commands, commands1, depends);
  326. } else {
  327. // No link script. Just use the link rule directly.
  328. commands1 = real_link_commands;
  329. }
  330. this->LocalGenerator->CreateCDCommand(
  331. commands1, this->Makefile->GetCurrentBinaryDirectory(),
  332. this->LocalGenerator->GetBinaryDirectory());
  333. cmAppend(commands, commands1);
  334. commands1.clear();
  335. // Compute the list of outputs.
  336. std::vector<std::string> outputs(1, targetOutputReal);
  337. // Write the build rule.
  338. this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
  339. commands, false);
  340. // Write the main driver rule to build everything in this target.
  341. this->WriteTargetDriverRule(targetOutputReal, relink);
  342. #else
  343. static_cast<void>(linkRuleVar);
  344. static_cast<void>(relink);
  345. #endif
  346. }
  347. void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
  348. const std::string& linkRuleVar, const std::string& extraFlags, bool relink)
  349. {
  350. // TODO: Merge the methods that call this method to avoid
  351. // code duplication.
  352. std::vector<std::string> commands;
  353. // Get the language to use for linking this library.
  354. std::string linkLanguage =
  355. this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
  356. // Make sure we have a link language.
  357. if (linkLanguage.empty()) {
  358. cmSystemTools::Error("Cannot determine link language for target \"" +
  359. this->GeneratorTarget->GetName() + "\".");
  360. return;
  361. }
  362. // Build list of dependencies.
  363. std::vector<std::string> depends;
  364. this->AppendLinkDepends(depends, linkLanguage);
  365. if (!this->DeviceLinkObject.empty()) {
  366. depends.push_back(this->DeviceLinkObject);
  367. }
  368. // Create set of linking flags.
  369. std::string linkFlags;
  370. this->LocalGenerator->AppendFlags(linkFlags, extraFlags);
  371. this->LocalGenerator->AppendIPOLinkerFlags(linkFlags, this->GeneratorTarget,
  372. this->ConfigName, linkLanguage);
  373. // Add OSX version flags, if any.
  374. if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  375. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  376. this->AppendOSXVerFlag(linkFlags, linkLanguage, "COMPATIBILITY", true);
  377. this->AppendOSXVerFlag(linkFlags, linkLanguage, "CURRENT", false);
  378. }
  379. // Construct the name of the library.
  380. this->GeneratorTarget->GetLibraryNames(this->ConfigName);
  381. // Construct the full path version of the names.
  382. std::string outpath;
  383. std::string outpathImp;
  384. if (this->GeneratorTarget->IsFrameworkOnApple()) {
  385. outpath = this->GeneratorTarget->GetDirectory(this->ConfigName);
  386. this->OSXBundleGenerator->CreateFramework(this->TargetNames.Output,
  387. outpath);
  388. outpath += '/';
  389. } else if (this->GeneratorTarget->IsCFBundleOnApple()) {
  390. outpath = this->GeneratorTarget->GetDirectory(this->ConfigName);
  391. this->OSXBundleGenerator->CreateCFBundle(this->TargetNames.Output,
  392. outpath);
  393. outpath += '/';
  394. } else if (relink) {
  395. outpath = cmStrCat(this->Makefile->GetCurrentBinaryDirectory(),
  396. "/CMakeFiles/CMakeRelink.dir");
  397. cmSystemTools::MakeDirectory(outpath);
  398. outpath += '/';
  399. if (!this->TargetNames.ImportLibrary.empty()) {
  400. outpathImp = outpath;
  401. }
  402. } else {
  403. outpath = this->GeneratorTarget->GetDirectory(this->ConfigName);
  404. cmSystemTools::MakeDirectory(outpath);
  405. outpath += '/';
  406. if (!this->TargetNames.ImportLibrary.empty()) {
  407. outpathImp = this->GeneratorTarget->GetDirectory(
  408. this->ConfigName, cmStateEnums::ImportLibraryArtifact);
  409. cmSystemTools::MakeDirectory(outpathImp);
  410. outpathImp += '/';
  411. }
  412. }
  413. std::string compilePdbOutputPath =
  414. this->GeneratorTarget->GetCompilePDBDirectory(this->ConfigName);
  415. cmSystemTools::MakeDirectory(compilePdbOutputPath);
  416. std::string pdbOutputPath =
  417. this->GeneratorTarget->GetPDBDirectory(this->ConfigName);
  418. cmSystemTools::MakeDirectory(pdbOutputPath);
  419. pdbOutputPath += "/";
  420. std::string targetFullPath = outpath + this->TargetNames.Output;
  421. std::string targetFullPathPDB = pdbOutputPath + this->TargetNames.PDB;
  422. std::string targetFullPathSO = outpath + this->TargetNames.SharedObject;
  423. std::string targetFullPathReal = outpath + this->TargetNames.Real;
  424. std::string targetFullPathImport =
  425. outpathImp + this->TargetNames.ImportLibrary;
  426. // Construct the output path version of the names for use in command
  427. // arguments.
  428. std::string targetOutPathPDB = this->LocalGenerator->ConvertToOutputFormat(
  429. targetFullPathPDB, cmOutputConverter::SHELL);
  430. std::string targetOutPath = this->LocalGenerator->ConvertToOutputFormat(
  431. this->LocalGenerator->MaybeConvertToRelativePath(
  432. this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPath),
  433. cmOutputConverter::SHELL);
  434. std::string targetOutPathSO = this->LocalGenerator->ConvertToOutputFormat(
  435. this->LocalGenerator->MaybeConvertToRelativePath(
  436. this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathSO),
  437. cmOutputConverter::SHELL);
  438. std::string targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
  439. this->LocalGenerator->MaybeConvertToRelativePath(
  440. this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
  441. cmOutputConverter::SHELL);
  442. std::string targetOutPathImport =
  443. this->LocalGenerator->ConvertToOutputFormat(
  444. this->LocalGenerator->MaybeConvertToRelativePath(
  445. this->LocalGenerator->GetCurrentBinaryDirectory(),
  446. targetFullPathImport),
  447. cmOutputConverter::SHELL);
  448. this->NumberOfProgressActions++;
  449. if (!this->NoRuleMessages) {
  450. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  451. this->MakeEchoProgress(progress);
  452. // Add the link message.
  453. std::string buildEcho = cmStrCat("Linking ", linkLanguage);
  454. switch (this->GeneratorTarget->GetType()) {
  455. case cmStateEnums::STATIC_LIBRARY:
  456. buildEcho += " static library ";
  457. break;
  458. case cmStateEnums::SHARED_LIBRARY:
  459. buildEcho += " shared library ";
  460. break;
  461. case cmStateEnums::MODULE_LIBRARY:
  462. if (this->GeneratorTarget->IsCFBundleOnApple()) {
  463. buildEcho += " CFBundle";
  464. }
  465. buildEcho += " shared module ";
  466. break;
  467. default:
  468. buildEcho += " library ";
  469. break;
  470. }
  471. buildEcho += targetOutPath;
  472. this->LocalGenerator->AppendEcho(
  473. commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
  474. }
  475. // Clean files associated with this library.
  476. std::set<std::string> libCleanFiles;
  477. libCleanFiles.insert(this->LocalGenerator->MaybeConvertToRelativePath(
  478. this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal));
  479. std::vector<std::string> commands1;
  480. // Add a command to remove any existing files for this library.
  481. // for static libs only
  482. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  483. this->LocalGenerator->AppendCleanCommand(commands1, libCleanFiles,
  484. this->GeneratorTarget, "target");
  485. this->LocalGenerator->CreateCDCommand(
  486. commands1, this->Makefile->GetCurrentBinaryDirectory(),
  487. this->LocalGenerator->GetBinaryDirectory());
  488. cmAppend(commands, commands1);
  489. commands1.clear();
  490. }
  491. if (this->TargetNames.Output != this->TargetNames.Real) {
  492. libCleanFiles.insert(this->LocalGenerator->MaybeConvertToRelativePath(
  493. this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPath));
  494. }
  495. if (this->TargetNames.SharedObject != this->TargetNames.Real &&
  496. this->TargetNames.SharedObject != this->TargetNames.Output) {
  497. libCleanFiles.insert(this->LocalGenerator->MaybeConvertToRelativePath(
  498. this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathSO));
  499. }
  500. if (!this->TargetNames.ImportLibrary.empty()) {
  501. libCleanFiles.insert(this->LocalGenerator->MaybeConvertToRelativePath(
  502. this->LocalGenerator->GetCurrentBinaryDirectory(),
  503. targetFullPathImport));
  504. std::string implib;
  505. if (this->GeneratorTarget->GetImplibGNUtoMS(
  506. this->ConfigName, targetFullPathImport, implib)) {
  507. libCleanFiles.insert(this->LocalGenerator->MaybeConvertToRelativePath(
  508. this->LocalGenerator->GetCurrentBinaryDirectory(), implib));
  509. }
  510. }
  511. // List the PDB for cleaning only when the whole target is
  512. // cleaned. We do not want to delete the .pdb file just before
  513. // linking the target.
  514. this->CleanFiles.insert(this->LocalGenerator->MaybeConvertToRelativePath(
  515. this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathPDB));
  516. #ifdef _WIN32
  517. // There may be a manifest file for this target. Add it to the
  518. // clean set just in case.
  519. if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
  520. libCleanFiles.insert(this->LocalGenerator->MaybeConvertToRelativePath(
  521. this->LocalGenerator->GetCurrentBinaryDirectory(),
  522. targetFullPath + ".manifest"));
  523. }
  524. #endif
  525. // Add the pre-build and pre-link rules building but not when relinking.
  526. if (!relink) {
  527. this->LocalGenerator->AppendCustomCommands(
  528. commands, this->GeneratorTarget->GetPreBuildCommands(),
  529. this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
  530. this->LocalGenerator->AppendCustomCommands(
  531. commands, this->GeneratorTarget->GetPreLinkCommands(),
  532. this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
  533. }
  534. // Determine whether a link script will be used.
  535. bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
  536. bool useResponseFileForObjects =
  537. this->CheckUseResponseFileForObjects(linkLanguage);
  538. bool const useResponseFileForLibs =
  539. this->CheckUseResponseFileForLibraries(linkLanguage);
  540. // For static libraries there might be archiving rules.
  541. bool haveStaticLibraryRule = false;
  542. std::vector<std::string> archiveCreateCommands;
  543. std::vector<std::string> archiveAppendCommands;
  544. std::vector<std::string> archiveFinishCommands;
  545. std::string::size_type archiveCommandLimit = std::string::npos;
  546. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  547. haveStaticLibraryRule = this->Makefile->IsDefinitionSet(linkRuleVar);
  548. std::string arCreateVar =
  549. cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_CREATE");
  550. arCreateVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  551. arCreateVar, linkLanguage, this->ConfigName);
  552. if (const char* rule = this->Makefile->GetDefinition(arCreateVar)) {
  553. cmExpandList(rule, archiveCreateCommands);
  554. }
  555. std::string arAppendVar =
  556. cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_APPEND");
  557. arAppendVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  558. arAppendVar, linkLanguage, this->ConfigName);
  559. if (const char* rule = this->Makefile->GetDefinition(arAppendVar)) {
  560. cmExpandList(rule, archiveAppendCommands);
  561. }
  562. std::string arFinishVar =
  563. cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_FINISH");
  564. arFinishVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  565. arFinishVar, linkLanguage, this->ConfigName);
  566. if (const char* rule = this->Makefile->GetDefinition(arFinishVar)) {
  567. cmExpandList(rule, archiveFinishCommands);
  568. }
  569. }
  570. // Decide whether to use archiving rules.
  571. bool useArchiveRules = !haveStaticLibraryRule &&
  572. !archiveCreateCommands.empty() && !archiveAppendCommands.empty();
  573. if (useArchiveRules) {
  574. // Archiving rules are always run with a link script.
  575. useLinkScript = true;
  576. // Archiving rules never use a response file.
  577. useResponseFileForObjects = false;
  578. // Limit the length of individual object lists to less than half of
  579. // the command line length limit (leaving half for other flags).
  580. // This may result in several calls to the archiver.
  581. if (size_t limit = cmSystemTools::CalculateCommandLineLengthLimit()) {
  582. archiveCommandLimit = limit / 2;
  583. } else {
  584. archiveCommandLimit = 8000;
  585. }
  586. }
  587. // Expand the rule variables.
  588. std::vector<std::string> real_link_commands;
  589. {
  590. bool useWatcomQuote =
  591. this->Makefile->IsOn(linkRuleVar + "_USE_WATCOM_QUOTE");
  592. // Set path conversion for link script shells.
  593. this->LocalGenerator->SetLinkScriptShell(useLinkScript);
  594. // Collect up flags to link in needed libraries.
  595. std::string linkLibs;
  596. if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
  597. std::unique_ptr<cmLinkLineComputer> linkLineComputer(
  598. this->CreateLinkLineComputer(
  599. this->LocalGenerator,
  600. this->LocalGenerator->GetStateSnapshot().GetDirectory()));
  601. linkLineComputer->SetForResponse(useResponseFileForLibs);
  602. linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
  603. linkLineComputer->SetRelink(relink);
  604. this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
  605. useResponseFileForLibs, depends);
  606. }
  607. // Construct object file lists that may be needed to expand the
  608. // rule.
  609. std::string buildObjs;
  610. this->CreateObjectLists(useLinkScript, useArchiveRules,
  611. useResponseFileForObjects, buildObjs, depends,
  612. useWatcomQuote);
  613. if (!this->DeviceLinkObject.empty()) {
  614. buildObjs += " " +
  615. this->LocalGenerator->ConvertToOutputFormat(
  616. this->LocalGenerator->MaybeConvertToRelativePath(
  617. this->LocalGenerator->GetCurrentBinaryDirectory(),
  618. this->DeviceLinkObject),
  619. cmOutputConverter::SHELL);
  620. }
  621. // maybe create .def file from list of objects
  622. this->GenDefFile(real_link_commands);
  623. std::string manifests = this->GetManifests();
  624. cmRulePlaceholderExpander::RuleVariables vars;
  625. vars.TargetPDB = targetOutPathPDB.c_str();
  626. // Setup the target version.
  627. std::string targetVersionMajor;
  628. std::string targetVersionMinor;
  629. {
  630. std::ostringstream majorStream;
  631. std::ostringstream minorStream;
  632. int major;
  633. int minor;
  634. this->GeneratorTarget->GetTargetVersion(major, minor);
  635. majorStream << major;
  636. minorStream << minor;
  637. targetVersionMajor = majorStream.str();
  638. targetVersionMinor = minorStream.str();
  639. }
  640. vars.TargetVersionMajor = targetVersionMajor.c_str();
  641. vars.TargetVersionMinor = targetVersionMinor.c_str();
  642. vars.CMTargetName = this->GeneratorTarget->GetName().c_str();
  643. vars.CMTargetType =
  644. cmState::GetTargetTypeName(this->GeneratorTarget->GetType());
  645. vars.Language = linkLanguage.c_str();
  646. vars.Objects = buildObjs.c_str();
  647. std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
  648. objectDir = this->LocalGenerator->ConvertToOutputFormat(
  649. this->LocalGenerator->MaybeConvertToRelativePath(
  650. this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
  651. cmOutputConverter::SHELL);
  652. vars.ObjectDir = objectDir.c_str();
  653. cmOutputConverter::OutputFormat output = (useWatcomQuote)
  654. ? cmOutputConverter::WATCOMQUOTE
  655. : cmOutputConverter::SHELL;
  656. std::string target = this->LocalGenerator->ConvertToOutputFormat(
  657. this->LocalGenerator->MaybeConvertToRelativePath(
  658. this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
  659. output);
  660. vars.Target = target.c_str();
  661. vars.LinkLibraries = linkLibs.c_str();
  662. vars.ObjectsQuoted = buildObjs.c_str();
  663. if (this->GeneratorTarget->HasSOName(this->ConfigName)) {
  664. vars.SONameFlag = this->Makefile->GetSONameFlag(linkLanguage);
  665. vars.TargetSOName = this->TargetNames.SharedObject.c_str();
  666. }
  667. vars.LinkFlags = linkFlags.c_str();
  668. vars.Manifests = manifests.c_str();
  669. // Compute the directory portion of the install_name setting.
  670. std::string install_name_dir;
  671. if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY) {
  672. // Get the install_name directory for the build tree.
  673. install_name_dir =
  674. this->GeneratorTarget->GetInstallNameDirForBuildTree(this->ConfigName);
  675. // Set the rule variable replacement value.
  676. if (install_name_dir.empty()) {
  677. vars.TargetInstallNameDir = "";
  678. } else {
  679. // Convert to a path for the native build tool.
  680. install_name_dir = this->LocalGenerator->ConvertToOutputFormat(
  681. install_name_dir, cmOutputConverter::SHELL);
  682. vars.TargetInstallNameDir = install_name_dir.c_str();
  683. }
  684. }
  685. // Add language-specific flags.
  686. std::string langFlags;
  687. this->LocalGenerator->AddLanguageFlagsForLinking(
  688. langFlags, this->GeneratorTarget, linkLanguage, this->ConfigName);
  689. this->LocalGenerator->AddArchitectureFlags(
  690. langFlags, this->GeneratorTarget, linkLanguage, this->ConfigName);
  691. vars.LanguageCompileFlags = langFlags.c_str();
  692. std::string launcher;
  693. const char* val = this->LocalGenerator->GetRuleLauncher(
  694. this->GeneratorTarget, "RULE_LAUNCH_LINK");
  695. if (val && *val) {
  696. launcher = cmStrCat(val, ' ');
  697. }
  698. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  699. this->LocalGenerator->CreateRulePlaceholderExpander());
  700. // Construct the main link rule and expand placeholders.
  701. rulePlaceholderExpander->SetTargetImpLib(targetOutPathImport);
  702. if (useArchiveRules) {
  703. // Construct the individual object list strings.
  704. std::vector<std::string> object_strings;
  705. this->WriteObjectsStrings(object_strings, archiveCommandLimit);
  706. // Add the cuda device object to the list of archive files. This will
  707. // only occur on archives which have CUDA_RESOLVE_DEVICE_SYMBOLS enabled
  708. if (!this->DeviceLinkObject.empty()) {
  709. object_strings.push_back(this->LocalGenerator->ConvertToOutputFormat(
  710. this->LocalGenerator->MaybeConvertToRelativePath(
  711. this->LocalGenerator->GetCurrentBinaryDirectory(),
  712. this->DeviceLinkObject),
  713. cmOutputConverter::SHELL));
  714. }
  715. // Create the archive with the first set of objects.
  716. std::vector<std::string>::iterator osi = object_strings.begin();
  717. {
  718. vars.Objects = osi->c_str();
  719. for (std::string const& acc : archiveCreateCommands) {
  720. std::string cmd = launcher + acc;
  721. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  722. cmd, vars);
  723. real_link_commands.push_back(std::move(cmd));
  724. }
  725. }
  726. // Append to the archive with the other object sets.
  727. for (++osi; osi != object_strings.end(); ++osi) {
  728. vars.Objects = osi->c_str();
  729. for (std::string const& aac : archiveAppendCommands) {
  730. std::string cmd = launcher + aac;
  731. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  732. cmd, vars);
  733. real_link_commands.push_back(std::move(cmd));
  734. }
  735. }
  736. // Finish the archive.
  737. vars.Objects = "";
  738. for (std::string const& afc : archiveFinishCommands) {
  739. std::string cmd = launcher + afc;
  740. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, cmd,
  741. vars);
  742. // If there is no ranlib the command will be ":". Skip it.
  743. if (!cmd.empty() && cmd[0] != ':') {
  744. real_link_commands.push_back(std::move(cmd));
  745. }
  746. }
  747. } else {
  748. // Get the set of commands.
  749. std::string linkRule = this->GetLinkRule(linkRuleVar);
  750. cmExpandList(linkRule, real_link_commands);
  751. if (this->GeneratorTarget->GetPropertyAsBool("LINK_WHAT_YOU_USE") &&
  752. (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY)) {
  753. std::string cmakeCommand = cmStrCat(
  754. this->LocalGenerator->ConvertToOutputFormat(
  755. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL),
  756. " -E __run_co_compile --lwyu=", targetOutPathReal);
  757. real_link_commands.push_back(std::move(cmakeCommand));
  758. }
  759. // Expand placeholders.
  760. for (std::string& real_link_command : real_link_commands) {
  761. real_link_command = cmStrCat(launcher, real_link_command);
  762. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  763. real_link_command, vars);
  764. }
  765. }
  766. // Restore path conversion to normal shells.
  767. this->LocalGenerator->SetLinkScriptShell(false);
  768. }
  769. // Optionally convert the build rule to use a script to avoid long
  770. // command lines in the make shell.
  771. if (useLinkScript) {
  772. // Use a link script.
  773. const char* name = (relink ? "relink.txt" : "link.txt");
  774. this->CreateLinkScript(name, real_link_commands, commands1, depends);
  775. } else {
  776. // No link script. Just use the link rule directly.
  777. commands1 = real_link_commands;
  778. }
  779. this->LocalGenerator->CreateCDCommand(
  780. commands1, this->Makefile->GetCurrentBinaryDirectory(),
  781. this->LocalGenerator->GetBinaryDirectory());
  782. cmAppend(commands, commands1);
  783. commands1.clear();
  784. // Add a rule to create necessary symlinks for the library.
  785. // Frameworks are handled by cmOSXBundleGenerator.
  786. if (targetOutPath != targetOutPathReal &&
  787. !this->GeneratorTarget->IsFrameworkOnApple()) {
  788. std::string symlink =
  789. cmStrCat("$(CMAKE_COMMAND) -E cmake_symlink_library ", targetOutPathReal,
  790. ' ', targetOutPathSO, ' ', targetOutPath);
  791. commands1.push_back(std::move(symlink));
  792. this->LocalGenerator->CreateCDCommand(
  793. commands1, this->Makefile->GetCurrentBinaryDirectory(),
  794. this->LocalGenerator->GetBinaryDirectory());
  795. cmAppend(commands, commands1);
  796. commands1.clear();
  797. }
  798. // Add the post-build rules when building but not when relinking.
  799. if (!relink) {
  800. this->LocalGenerator->AppendCustomCommands(
  801. commands, this->GeneratorTarget->GetPostBuildCommands(),
  802. this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
  803. }
  804. // Compute the list of outputs.
  805. std::vector<std::string> outputs(1, targetFullPathReal);
  806. if (this->TargetNames.SharedObject != this->TargetNames.Real) {
  807. outputs.push_back(targetFullPathSO);
  808. }
  809. if (this->TargetNames.Output != this->TargetNames.SharedObject &&
  810. this->TargetNames.Output != this->TargetNames.Real) {
  811. outputs.push_back(targetFullPath);
  812. }
  813. // Write the build rule.
  814. this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
  815. commands, false);
  816. // Write the main driver rule to build everything in this target.
  817. this->WriteTargetDriverRule(targetFullPath, relink);
  818. // Clean all the possible library names and symlinks.
  819. this->CleanFiles.insert(libCleanFiles.begin(), libCleanFiles.end());
  820. }