cmMakefileLibraryTargetGenerator.cxx 36 KB

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