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"
12 #include <cmext/algorithm>
14 #include "cmGeneratedFileStream.h"
15 #include "cmGeneratorTarget.h"
16 #include "cmGlobalUnixMakefileGenerator3.h"
17 #include "cmLinkLineComputer.h"
18 #include "cmLinkLineDeviceComputer.h"
19 #include "cmLocalGenerator.h"
20 #include "cmLocalUnixMakefileGenerator3.h"
21 #include "cmMakefile.h"
22 #include "cmOSXBundleGenerator.h"
23 #include "cmOutputConverter.h"
24 #include "cmRulePlaceholderExpander.h"
26 #include "cmStateDirectory.h"
27 #include "cmStateSnapshot.h"
28 #include "cmStateTypes.h"
29 #include "cmStringAlgorithms.h"
30 #include "cmSystemTools.h"
33 cmMakefileLibraryTargetGenerator::cmMakefileLibraryTargetGenerator(
34 cmGeneratorTarget* target)
35 : cmMakefileTargetGenerator(target)
37 this->CustomCommandDriver = OnDepends;
38 if (this->GeneratorTarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
40 this->GeneratorTarget->GetLibraryNames(this->GetConfigName());
43 this->OSXBundleGenerator = cm::make_unique<cmOSXBundleGenerator>(target);
44 this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders);
47 cmMakefileLibraryTargetGenerator::~cmMakefileLibraryTargetGenerator() =
50 void cmMakefileLibraryTargetGenerator::WriteRuleFiles()
52 // create the build.make file and directory, put in the common blocks
53 this->CreateRuleFile();
55 // write rules used to help build object files
56 this->WriteCommonCodeRules();
58 // write the per-target per-language flags
59 this->WriteTargetLanguageFlags();
61 // write in rules for object files and custom commands
62 this->WriteTargetBuildRules();
64 // write the link rules
65 // Write the rule for this target type.
66 switch (this->GeneratorTarget->GetType()) {
67 case cmStateEnums::STATIC_LIBRARY:
68 this->WriteStaticLibraryRules();
70 case cmStateEnums::SHARED_LIBRARY:
71 this->WriteSharedLibraryRules(false);
72 if (this->GeneratorTarget->NeedRelinkBeforeInstall(
73 this->GetConfigName())) {
74 // Write rules to link an installable version of the target.
75 this->WriteSharedLibraryRules(true);
78 case cmStateEnums::MODULE_LIBRARY:
79 this->WriteModuleLibraryRules(false);
80 if (this->GeneratorTarget->NeedRelinkBeforeInstall(
81 this->GetConfigName())) {
82 // Write rules to link an installable version of the target.
83 this->WriteModuleLibraryRules(true);
86 case cmStateEnums::OBJECT_LIBRARY:
87 this->WriteObjectLibraryRules();
90 // If language is not known, this is an error.
91 cmSystemTools::Error("Unknown Library Type");
96 this->WriteTargetCleanRules();
98 // Write the dependency generation rule. This must be done last so
99 // that multiple output pair information is available.
100 this->WriteTargetDependRules();
103 this->CloseFileStreams();
106 void cmMakefileLibraryTargetGenerator::WriteObjectLibraryRules()
108 std::vector<std::string> commands;
109 std::vector<std::string> depends;
111 // Add post-build rules.
112 this->LocalGenerator->AppendCustomCommands(
113 commands, this->GeneratorTarget->GetPostBuildCommands(),
114 this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
116 // Depend on the object files.
117 this->AppendObjectDepends(depends);
120 this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
121 this->GeneratorTarget->GetName(),
122 depends, commands, true);
124 // Write the main driver rule to build everything in this target.
125 this->WriteTargetDriverRule(this->GeneratorTarget->GetName(), false);
128 void cmMakefileLibraryTargetGenerator::WriteStaticLibraryRules()
130 const bool requiresDeviceLinking = requireDeviceLinking(
131 *this->GeneratorTarget, *this->LocalGenerator, this->GetConfigName());
132 if (requiresDeviceLinking) {
133 this->WriteDeviceLibraryRules("CMAKE_CUDA_DEVICE_LINK_LIBRARY", false);
136 std::string linkLanguage =
137 this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
139 std::string linkRuleVar = this->GeneratorTarget->GetCreateRuleVariable(
140 linkLanguage, this->GetConfigName());
142 std::string extraFlags;
143 this->LocalGenerator->GetStaticLibraryFlags(
144 extraFlags, this->GetConfigName(), linkLanguage, this->GeneratorTarget);
145 this->WriteLibraryRules(linkRuleVar, extraFlags, false);
148 void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink)
150 if (this->GeneratorTarget->IsFrameworkOnApple()) {
151 this->WriteFrameworkRules(relink);
156 const bool requiresDeviceLinking = requireDeviceLinking(
157 *this->GeneratorTarget, *this->LocalGenerator, this->GetConfigName());
158 if (requiresDeviceLinking) {
159 this->WriteDeviceLibraryRules("CMAKE_CUDA_DEVICE_LINK_LIBRARY", relink);
163 std::string linkLanguage =
164 this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
165 std::string linkRuleVar =
166 cmStrCat("CMAKE_", linkLanguage, "_CREATE_SHARED_LIBRARY");
168 std::string extraFlags;
169 this->GetTargetLinkFlags(extraFlags, linkLanguage);
170 this->LocalGenerator->AddConfigVariableFlags(
171 extraFlags, "CMAKE_SHARED_LINKER_FLAGS", this->GetConfigName());
173 std::unique_ptr<cmLinkLineComputer> linkLineComputer =
174 this->CreateLinkLineComputer(
175 this->LocalGenerator,
176 this->LocalGenerator->GetStateSnapshot().GetDirectory());
178 this->LocalGenerator->AppendModuleDefinitionFlag(
179 extraFlags, this->GeneratorTarget, linkLineComputer.get(),
180 this->GetConfigName());
182 this->UseLWYU = this->LocalGenerator->AppendLWYUFlags(
183 extraFlags, this->GeneratorTarget, linkLanguage);
185 this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
188 void cmMakefileLibraryTargetGenerator::WriteModuleLibraryRules(bool relink)
191 const bool requiresDeviceLinking = requireDeviceLinking(
192 *this->GeneratorTarget, *this->LocalGenerator, this->GetConfigName());
193 if (requiresDeviceLinking) {
194 this->WriteDeviceLibraryRules("CMAKE_CUDA_DEVICE_LINK_LIBRARY", relink);
198 std::string linkLanguage =
199 this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
200 std::string linkRuleVar =
201 cmStrCat("CMAKE_", linkLanguage, "_CREATE_SHARED_MODULE");
203 std::string extraFlags;
204 this->GetTargetLinkFlags(extraFlags, linkLanguage);
205 this->LocalGenerator->AddConfigVariableFlags(
206 extraFlags, "CMAKE_MODULE_LINKER_FLAGS", this->GetConfigName());
208 std::unique_ptr<cmLinkLineComputer> linkLineComputer =
209 this->CreateLinkLineComputer(
210 this->LocalGenerator,
211 this->LocalGenerator->GetStateSnapshot().GetDirectory());
213 this->LocalGenerator->AppendModuleDefinitionFlag(
214 extraFlags, this->GeneratorTarget, linkLineComputer.get(),
215 this->GetConfigName());
217 this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
220 void cmMakefileLibraryTargetGenerator::WriteFrameworkRules(bool relink)
222 std::string linkLanguage =
223 this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
224 std::string linkRuleVar =
225 cmStrCat("CMAKE_", linkLanguage, "_CREATE_MACOSX_FRAMEWORK");
227 std::string extraFlags;
228 this->GetTargetLinkFlags(extraFlags, linkLanguage);
229 this->LocalGenerator->AddConfigVariableFlags(
230 extraFlags, "CMAKE_MACOSX_FRAMEWORK_LINKER_FLAGS", this->GetConfigName());
232 this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
235 void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules(
236 const std::string& linkRuleVar, bool relink)
238 #ifndef CMAKE_BOOTSTRAP
239 // TODO: Merge the methods that call this method to avoid
241 std::vector<std::string> commands;
242 std::string const objExt =
243 this->Makefile->GetSafeDefinition("CMAKE_CUDA_OUTPUT_EXTENSION");
245 // Get the name of the device object to generate.
246 std::string const targetOutput =
247 this->GeneratorTarget->ObjectDirectory + "cmake_device_link" + objExt;
248 this->DeviceLinkObject = targetOutput;
250 this->NumberOfProgressActions++;
251 if (!this->NoRuleMessages) {
252 cmLocalUnixMakefileGenerator3::EchoProgress progress;
253 this->MakeEchoProgress(progress);
254 // Add the link message.
255 std::string buildEcho = cmStrCat(
256 "Linking CUDA device code ",
257 this->LocalGenerator->ConvertToOutputFormat(
258 this->LocalGenerator->MaybeRelativeToCurBinDir(this->DeviceLinkObject),
259 cmOutputConverter::SHELL));
260 this->LocalGenerator->AppendEcho(
261 commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
264 if (this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID") == "Clang") {
265 this->WriteDeviceLinkRule(commands, targetOutput);
267 this->WriteNvidiaDeviceLibraryRules(linkRuleVar, relink, commands,
271 // Write the main driver rule to build everything in this target.
272 this->WriteTargetDriverRule(targetOutput, relink);
275 void cmMakefileLibraryTargetGenerator::WriteNvidiaDeviceLibraryRules(
276 const std::string& linkRuleVar, bool relink,
277 std::vector<std::string>& commands, const std::string& targetOutput)
279 std::string linkLanguage = "CUDA";
281 // Build list of dependencies.
282 std::vector<std::string> depends;
283 this->AppendLinkDepends(depends, linkLanguage);
285 // Add language-specific flags.
286 std::string langFlags;
287 this->LocalGenerator->AddLanguageFlagsForLinking(
288 langFlags, this->GeneratorTarget, linkLanguage, this->GetConfigName());
290 // Create set of linking flags.
291 std::string linkFlags;
292 this->GetDeviceLinkFlags(linkFlags, linkLanguage);
294 // Clean files associated with this library.
295 std::set<std::string> libCleanFiles;
296 libCleanFiles.insert(
297 this->LocalGenerator->MaybeRelativeToCurBinDir(targetOutput));
299 // Determine whether a link script will be used.
300 bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
302 bool useResponseFileForObjects =
303 this->CheckUseResponseFileForObjects(linkLanguage);
304 bool const useResponseFileForLibs =
305 this->CheckUseResponseFileForLibraries(linkLanguage);
307 cmRulePlaceholderExpander::RuleVariables vars;
308 vars.Language = linkLanguage.c_str();
310 // Expand the rule variables.
311 std::vector<std::string> real_link_commands;
313 // Set path conversion for link script shells.
314 this->LocalGenerator->SetLinkScriptShell(useLinkScript);
316 // Collect up flags to link in needed libraries.
317 std::string linkLibs;
318 std::unique_ptr<cmLinkLineComputer> linkLineComputer(
319 new cmLinkLineDeviceComputer(
320 this->LocalGenerator,
321 this->LocalGenerator->GetStateSnapshot().GetDirectory()));
322 linkLineComputer->SetForResponse(useResponseFileForLibs);
323 linkLineComputer->SetRelink(relink);
325 this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
326 useResponseFileForLibs, depends);
328 // Construct object file lists that may be needed to expand the
330 std::string buildObjs;
331 this->CreateObjectLists(useLinkScript, false, // useArchiveRules
332 useResponseFileForObjects, buildObjs, depends,
335 std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
336 objectDir = this->LocalGenerator->ConvertToOutputFormat(
337 this->LocalGenerator->MaybeRelativeToCurBinDir(objectDir),
338 cmOutputConverter::SHELL);
340 std::string target = this->LocalGenerator->ConvertToOutputFormat(
341 this->LocalGenerator->MaybeRelativeToCurBinDir(targetOutput),
342 cmOutputConverter::SHELL);
344 std::string targetFullPathCompilePDB =
345 this->ComputeTargetCompilePDB(this->GetConfigName());
346 std::string targetOutPathCompilePDB =
347 this->LocalGenerator->ConvertToOutputFormat(targetFullPathCompilePDB,
348 cmOutputConverter::SHELL);
350 vars.Objects = buildObjs.c_str();
351 vars.ObjectDir = objectDir.c_str();
352 vars.Target = target.c_str();
353 vars.LinkLibraries = linkLibs.c_str();
354 vars.ObjectsQuoted = buildObjs.c_str();
355 vars.LanguageCompileFlags = langFlags.c_str();
356 vars.LinkFlags = linkFlags.c_str();
357 vars.TargetCompilePDB = targetOutPathCompilePDB.c_str();
359 std::string launcher;
360 cmValue val = this->LocalGenerator->GetRuleLauncher(this->GeneratorTarget,
362 if (cmNonempty(val)) {
363 launcher = cmStrCat(*val, ' ');
366 std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
367 this->LocalGenerator->CreateRulePlaceholderExpander());
369 // Construct the main link rule and expand placeholders.
370 rulePlaceholderExpander->SetTargetImpLib(targetOutput);
371 std::string linkRule = this->GetLinkRule(linkRuleVar);
372 cmExpandList(linkRule, real_link_commands);
374 // Expand placeholders.
375 for (std::string& real_link_command : real_link_commands) {
376 real_link_command = cmStrCat(launcher, real_link_command);
377 rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
378 real_link_command, vars);
380 // Restore path conversion to normal shells.
381 this->LocalGenerator->SetLinkScriptShell(false);
383 // Clean all the possible library names and symlinks.
384 this->CleanFiles.insert(libCleanFiles.begin(), libCleanFiles.end());
387 std::vector<std::string> commands1;
388 // Optionally convert the build rule to use a script to avoid long
389 // command lines in the make shell.
391 // Use a link script.
392 const char* name = (relink ? "drelink.txt" : "dlink.txt");
393 this->CreateLinkScript(name, real_link_commands, commands1, depends);
395 // No link script. Just use the link rule directly.
396 commands1 = real_link_commands;
398 this->LocalGenerator->CreateCDCommand(
399 commands1, this->Makefile->GetCurrentBinaryDirectory(),
400 this->LocalGenerator->GetBinaryDirectory());
401 cm::append(commands, commands1);
404 // Compute the list of outputs.
405 std::vector<std::string> outputs(1, targetOutput);
407 // Write the build rule.
408 this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
411 static_cast<void>(linkRuleVar);
412 static_cast<void>(relink);
416 void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
417 const std::string& linkRuleVar, const std::string& extraFlags, bool relink)
419 // TODO: Merge the methods that call this method to avoid
421 std::vector<std::string> commands;
423 // Get the language to use for linking this library.
424 std::string linkLanguage =
425 this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
427 // Make sure we have a link language.
428 if (linkLanguage.empty()) {
429 cmSystemTools::Error("Cannot determine link language for target \"" +
430 this->GeneratorTarget->GetName() + "\".");
434 // Build list of dependencies.
435 std::vector<std::string> depends;
436 this->AppendLinkDepends(depends, linkLanguage);
437 if (!this->DeviceLinkObject.empty()) {
438 depends.push_back(this->DeviceLinkObject);
441 // Create set of linking flags.
442 std::string linkFlags;
443 this->LocalGenerator->AppendFlags(linkFlags, extraFlags);
444 this->LocalGenerator->AppendIPOLinkerFlags(
445 linkFlags, this->GeneratorTarget, this->GetConfigName(), linkLanguage);
447 // Add OSX version flags, if any.
448 if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
449 this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
450 this->AppendOSXVerFlag(linkFlags, linkLanguage, "COMPATIBILITY", true);
451 this->AppendOSXVerFlag(linkFlags, linkLanguage, "CURRENT", false);
454 // Construct the name of the library.
455 this->GeneratorTarget->GetLibraryNames(this->GetConfigName());
457 // Construct the full path version of the names.
459 std::string outpathImp;
460 if (this->GeneratorTarget->IsFrameworkOnApple()) {
461 outpath = this->GeneratorTarget->GetDirectory(this->GetConfigName());
462 this->OSXBundleGenerator->CreateFramework(this->TargetNames.Output,
463 outpath, this->GetConfigName());
465 } else if (this->GeneratorTarget->IsCFBundleOnApple()) {
466 outpath = this->GeneratorTarget->GetDirectory(this->GetConfigName());
467 this->OSXBundleGenerator->CreateCFBundle(this->TargetNames.Output, outpath,
468 this->GetConfigName());
471 outpath = cmStrCat(this->Makefile->GetCurrentBinaryDirectory(),
472 "/CMakeFiles/CMakeRelink.dir");
473 cmSystemTools::MakeDirectory(outpath);
475 if (!this->TargetNames.ImportLibrary.empty()) {
476 outpathImp = outpath;
479 outpath = this->GeneratorTarget->GetDirectory(this->GetConfigName());
480 cmSystemTools::MakeDirectory(outpath);
482 if (!this->TargetNames.ImportLibrary.empty()) {
483 outpathImp = this->GeneratorTarget->GetDirectory(
484 this->GetConfigName(), cmStateEnums::ImportLibraryArtifact);
485 cmSystemTools::MakeDirectory(outpathImp);
490 std::string compilePdbOutputPath =
491 this->GeneratorTarget->GetCompilePDBDirectory(this->GetConfigName());
492 cmSystemTools::MakeDirectory(compilePdbOutputPath);
494 std::string pdbOutputPath =
495 this->GeneratorTarget->GetPDBDirectory(this->GetConfigName());
496 cmSystemTools::MakeDirectory(pdbOutputPath);
497 pdbOutputPath += "/";
499 std::string targetFullPath = outpath + this->TargetNames.Output;
500 std::string targetFullPathPDB = pdbOutputPath + this->TargetNames.PDB;
501 std::string targetFullPathSO = outpath + this->TargetNames.SharedObject;
502 std::string targetFullPathReal = outpath + this->TargetNames.Real;
503 std::string targetFullPathImport =
504 outpathImp + this->TargetNames.ImportLibrary;
506 // Construct the output path version of the names for use in command
508 std::string targetOutPathPDB = this->LocalGenerator->ConvertToOutputFormat(
509 targetFullPathPDB, cmOutputConverter::SHELL);
511 std::string targetOutPath = this->LocalGenerator->ConvertToOutputFormat(
512 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPath),
513 cmOutputConverter::SHELL);
514 std::string targetOutPathSO = this->LocalGenerator->ConvertToOutputFormat(
515 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathSO),
516 cmOutputConverter::SHELL);
517 std::string targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
518 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathReal),
519 cmOutputConverter::SHELL);
520 std::string targetOutPathImport =
521 this->LocalGenerator->ConvertToOutputFormat(
522 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathImport),
523 cmOutputConverter::SHELL);
525 this->NumberOfProgressActions++;
526 if (!this->NoRuleMessages) {
527 cmLocalUnixMakefileGenerator3::EchoProgress progress;
528 this->MakeEchoProgress(progress);
529 // Add the link message.
530 std::string buildEcho = cmStrCat("Linking ", linkLanguage);
531 switch (this->GeneratorTarget->GetType()) {
532 case cmStateEnums::STATIC_LIBRARY:
533 buildEcho += " static library ";
535 case cmStateEnums::SHARED_LIBRARY:
536 buildEcho += " shared library ";
538 case cmStateEnums::MODULE_LIBRARY:
539 if (this->GeneratorTarget->IsCFBundleOnApple()) {
540 buildEcho += " CFBundle";
542 buildEcho += " shared module ";
545 buildEcho += " library ";
548 buildEcho += targetOutPath;
549 this->LocalGenerator->AppendEcho(
550 commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
553 // Clean files associated with this library.
554 std::set<std::string> libCleanFiles;
555 libCleanFiles.insert(
556 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathReal));
558 std::vector<std::string> commands1;
559 // Add a command to remove any existing files for this library.
560 // for static libs only
561 if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
562 this->LocalGenerator->AppendCleanCommand(commands1, libCleanFiles,
563 this->GeneratorTarget, "target");
564 this->LocalGenerator->CreateCDCommand(
565 commands1, this->Makefile->GetCurrentBinaryDirectory(),
566 this->LocalGenerator->GetBinaryDirectory());
567 cm::append(commands, commands1);
571 if (this->TargetNames.Output != this->TargetNames.Real) {
572 libCleanFiles.insert(
573 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPath));
575 if (this->TargetNames.SharedObject != this->TargetNames.Real &&
576 this->TargetNames.SharedObject != this->TargetNames.Output) {
577 libCleanFiles.insert(
578 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathSO));
580 if (!this->TargetNames.ImportLibrary.empty()) {
581 libCleanFiles.insert(
582 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathImport));
584 if (this->GeneratorTarget->GetImplibGNUtoMS(
585 this->GetConfigName(), targetFullPathImport, implib)) {
586 libCleanFiles.insert(
587 this->LocalGenerator->MaybeRelativeToCurBinDir(implib));
591 // List the PDB for cleaning only when the whole target is
592 // cleaned. We do not want to delete the .pdb file just before
593 // linking the target.
594 this->CleanFiles.insert(
595 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathPDB));
598 // There may be a manifest file for this target. Add it to the
599 // clean set just in case.
600 if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
601 libCleanFiles.insert(this->LocalGenerator->MaybeRelativeToCurBinDir(
602 targetFullPath + ".manifest"));
606 // Add the pre-build and pre-link rules building but not when relinking.
608 this->LocalGenerator->AppendCustomCommands(
609 commands, this->GeneratorTarget->GetPreBuildCommands(),
610 this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
611 this->LocalGenerator->AppendCustomCommands(
612 commands, this->GeneratorTarget->GetPreLinkCommands(),
613 this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
616 // Determine whether a link script will be used.
617 bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
619 bool useResponseFileForObjects =
620 this->CheckUseResponseFileForObjects(linkLanguage);
621 bool const useResponseFileForLibs =
622 this->CheckUseResponseFileForLibraries(linkLanguage);
624 // For static libraries there might be archiving rules.
625 bool haveStaticLibraryRule = false;
626 std::vector<std::string> archiveCreateCommands;
627 std::vector<std::string> archiveAppendCommands;
628 std::vector<std::string> archiveFinishCommands;
629 std::string::size_type archiveCommandLimit = std::string::npos;
630 if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
631 haveStaticLibraryRule = this->Makefile->IsDefinitionSet(linkRuleVar);
632 std::string arCreateVar =
633 cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_CREATE");
635 arCreateVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
636 arCreateVar, linkLanguage, this->GetConfigName());
638 this->Makefile->GetDefExpandList(arCreateVar, archiveCreateCommands);
639 std::string arAppendVar =
640 cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_APPEND");
642 arAppendVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
643 arAppendVar, linkLanguage, this->GetConfigName());
645 this->Makefile->GetDefExpandList(arAppendVar, archiveAppendCommands);
646 std::string arFinishVar =
647 cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_FINISH");
649 arFinishVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
650 arFinishVar, linkLanguage, this->GetConfigName());
652 this->Makefile->GetDefExpandList(arFinishVar, archiveFinishCommands);
655 // Decide whether to use archiving rules.
656 bool useArchiveRules = !haveStaticLibraryRule &&
657 !archiveCreateCommands.empty() && !archiveAppendCommands.empty();
658 if (useArchiveRules) {
659 // Archiving rules are always run with a link script.
660 useLinkScript = true;
662 // Archiving rules never use a response file.
663 useResponseFileForObjects = false;
665 // Limit the length of individual object lists to less than half of
666 // the command line length limit (leaving half for other flags).
667 // This may result in several calls to the archiver.
668 if (size_t limit = cmSystemTools::CalculateCommandLineLengthLimit()) {
669 archiveCommandLimit = limit / 2;
671 archiveCommandLimit = 8000;
675 // Expand the rule variables.
676 std::vector<std::string> real_link_commands;
678 bool useWatcomQuote =
679 this->Makefile->IsOn(linkRuleVar + "_USE_WATCOM_QUOTE");
681 // Set path conversion for link script shells.
682 this->LocalGenerator->SetLinkScriptShell(useLinkScript);
684 // Collect up flags to link in needed libraries.
685 std::string linkLibs;
686 if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
688 std::unique_ptr<cmLinkLineComputer> linkLineComputer =
689 this->CreateLinkLineComputer(
690 this->LocalGenerator,
691 this->LocalGenerator->GetStateSnapshot().GetDirectory());
692 linkLineComputer->SetForResponse(useResponseFileForLibs);
693 linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
694 linkLineComputer->SetRelink(relink);
696 this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
697 useResponseFileForLibs, depends);
700 // Construct object file lists that may be needed to expand the
702 std::string buildObjs;
703 this->CreateObjectLists(useLinkScript, useArchiveRules,
704 useResponseFileForObjects, buildObjs, depends,
706 if (!this->DeviceLinkObject.empty()) {
708 this->LocalGenerator->ConvertToOutputFormat(
709 this->LocalGenerator->MaybeRelativeToCurBinDir(
710 this->DeviceLinkObject),
711 cmOutputConverter::SHELL);
714 std::string const& aixExports = this->GetAIXExports(this->GetConfigName());
716 // maybe create .def file from list of objects
717 this->GenDefFile(real_link_commands);
719 std::string manifests = this->GetManifests(this->GetConfigName());
721 cmRulePlaceholderExpander::RuleVariables vars;
722 vars.TargetPDB = targetOutPathPDB.c_str();
724 // Setup the target version.
725 std::string targetVersionMajor;
726 std::string targetVersionMinor;
728 std::ostringstream majorStream;
729 std::ostringstream minorStream;
732 this->GeneratorTarget->GetTargetVersion(major, minor);
733 majorStream << major;
734 minorStream << minor;
735 targetVersionMajor = majorStream.str();
736 targetVersionMinor = minorStream.str();
738 vars.TargetVersionMajor = targetVersionMajor.c_str();
739 vars.TargetVersionMinor = targetVersionMinor.c_str();
741 vars.CMTargetName = this->GeneratorTarget->GetName().c_str();
743 cmState::GetTargetTypeName(this->GeneratorTarget->GetType()).c_str();
744 vars.Language = linkLanguage.c_str();
745 vars.AIXExports = aixExports.c_str();
746 vars.Objects = buildObjs.c_str();
747 std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
749 objectDir = this->LocalGenerator->ConvertToOutputFormat(
750 this->LocalGenerator->MaybeRelativeToCurBinDir(objectDir),
751 cmOutputConverter::SHELL);
753 vars.ObjectDir = objectDir.c_str();
754 cmOutputConverter::OutputFormat output = (useWatcomQuote)
755 ? cmOutputConverter::WATCOMQUOTE
756 : cmOutputConverter::SHELL;
757 std::string target = this->LocalGenerator->ConvertToOutputFormat(
758 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathReal),
760 vars.Target = target.c_str();
761 vars.LinkLibraries = linkLibs.c_str();
762 vars.ObjectsQuoted = buildObjs.c_str();
763 std::string targetOutSOName;
764 if (this->GeneratorTarget->HasSOName(this->GetConfigName())) {
765 vars.SONameFlag = this->Makefile->GetSONameFlag(linkLanguage);
766 targetOutSOName = this->LocalGenerator->ConvertToOutputFormat(
767 this->TargetNames.SharedObject.c_str(), cmOutputConverter::SHELL);
768 vars.TargetSOName = targetOutSOName.c_str();
770 vars.LinkFlags = linkFlags.c_str();
772 vars.Manifests = manifests.c_str();
774 // Compute the directory portion of the install_name setting.
775 std::string install_name_dir;
776 if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY) {
777 // Get the install_name directory for the build tree.
778 install_name_dir = this->GeneratorTarget->GetInstallNameDirForBuildTree(
779 this->GetConfigName());
781 // Set the rule variable replacement value.
782 if (install_name_dir.empty()) {
783 vars.TargetInstallNameDir = "";
785 // Convert to a path for the native build tool.
786 install_name_dir = this->LocalGenerator->ConvertToOutputFormat(
787 install_name_dir, cmOutputConverter::SHELL);
788 vars.TargetInstallNameDir = install_name_dir.c_str();
792 // Add language-specific flags.
793 std::string langFlags;
794 this->LocalGenerator->AddLanguageFlagsForLinking(
795 langFlags, this->GeneratorTarget, linkLanguage, this->GetConfigName());
797 this->LocalGenerator->AddArchitectureFlags(
798 langFlags, this->GeneratorTarget, linkLanguage, this->GetConfigName());
800 vars.LanguageCompileFlags = langFlags.c_str();
802 std::string linkerLauncher =
803 this->GetLinkerLauncher(this->GetConfigName());
804 if (cmNonempty(linkerLauncher)) {
805 vars.Launcher = linkerLauncher.c_str();
808 std::string launcher;
809 cmValue val = this->LocalGenerator->GetRuleLauncher(this->GeneratorTarget,
811 if (cmNonempty(val)) {
812 launcher = cmStrCat(*val, ' ');
815 std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
816 this->LocalGenerator->CreateRulePlaceholderExpander());
817 // Construct the main link rule and expand placeholders.
818 rulePlaceholderExpander->SetTargetImpLib(targetOutPathImport);
819 if (useArchiveRules) {
820 // Construct the individual object list strings.
821 std::vector<std::string> object_strings;
822 this->WriteObjectsStrings(object_strings, archiveCommandLimit);
824 // Add the cuda device object to the list of archive files. This will
825 // only occur on archives which have CUDA_RESOLVE_DEVICE_SYMBOLS enabled
826 if (!this->DeviceLinkObject.empty()) {
827 object_strings.push_back(this->LocalGenerator->ConvertToOutputFormat(
828 this->LocalGenerator->MaybeRelativeToCurBinDir(
829 this->DeviceLinkObject),
830 cmOutputConverter::SHELL));
833 // Create the archive with the first set of objects.
834 auto osi = object_strings.begin();
836 vars.Objects = osi->c_str();
837 for (std::string const& acc : archiveCreateCommands) {
838 std::string cmd = launcher + acc;
839 rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
841 real_link_commands.push_back(std::move(cmd));
844 // Append to the archive with the other object sets.
845 for (++osi; osi != object_strings.end(); ++osi) {
846 vars.Objects = osi->c_str();
847 for (std::string const& aac : archiveAppendCommands) {
848 std::string cmd = launcher + aac;
849 rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
851 real_link_commands.push_back(std::move(cmd));
854 // Finish the archive.
856 for (std::string const& afc : archiveFinishCommands) {
857 std::string cmd = launcher + afc;
858 rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, cmd,
860 // If there is no ranlib the command will be ":". Skip it.
861 if (!cmd.empty() && cmd[0] != ':') {
862 real_link_commands.push_back(std::move(cmd));
866 // Get the set of commands.
867 std::string linkRule = this->GetLinkRule(linkRuleVar);
868 cmExpandList(linkRule, real_link_commands);
871 this->Makefile->GetDefinition("CMAKE_LINK_WHAT_YOU_USE_CHECK");
873 std::string cmakeCommand = cmStrCat(
874 this->LocalGenerator->ConvertToOutputFormat(
875 cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL),
876 " -E __run_co_compile --lwyu=");
877 cmakeCommand += this->LocalGenerator->EscapeForShell(*lwyuCheck);
878 cmakeCommand += cmStrCat(" --source=", targetOutPathReal);
879 real_link_commands.push_back(std::move(cmakeCommand));
883 // Expand placeholders.
884 for (std::string& real_link_command : real_link_commands) {
885 real_link_command = cmStrCat(launcher, real_link_command);
886 rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
887 real_link_command, vars);
891 // Restore path conversion to normal shells.
892 this->LocalGenerator->SetLinkScriptShell(false);
895 // Optionally convert the build rule to use a script to avoid long
896 // command lines in the make shell.
898 // Use a link script.
899 const char* name = (relink ? "relink.txt" : "link.txt");
900 this->CreateLinkScript(name, real_link_commands, commands1, depends);
902 // No link script. Just use the link rule directly.
903 commands1 = real_link_commands;
905 this->LocalGenerator->CreateCDCommand(
906 commands1, this->Makefile->GetCurrentBinaryDirectory(),
907 this->LocalGenerator->GetBinaryDirectory());
908 cm::append(commands, commands1);
911 // Add a rule to create necessary symlinks for the library.
912 // Frameworks are handled by cmOSXBundleGenerator.
913 if (targetOutPath != targetOutPathReal &&
914 !this->GeneratorTarget->IsFrameworkOnApple()) {
915 std::string symlink =
916 cmStrCat("$(CMAKE_COMMAND) -E cmake_symlink_library ", targetOutPathReal,
917 ' ', targetOutPathSO, ' ', targetOutPath);
918 commands1.push_back(std::move(symlink));
919 this->LocalGenerator->CreateCDCommand(
920 commands1, this->Makefile->GetCurrentBinaryDirectory(),
921 this->LocalGenerator->GetBinaryDirectory());
922 cm::append(commands, commands1);
926 // Add the post-build rules when building but not when relinking.
928 this->LocalGenerator->AppendCustomCommands(
929 commands, this->GeneratorTarget->GetPostBuildCommands(),
930 this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
933 // Compute the list of outputs.
934 std::vector<std::string> outputs;
936 outputs.push_back(targetFullPathReal);
937 if (this->TargetNames.SharedObject != this->TargetNames.Real) {
938 outputs.push_back(targetFullPathSO);
940 if (this->TargetNames.Output != this->TargetNames.SharedObject &&
941 this->TargetNames.Output != this->TargetNames.Real) {
942 outputs.push_back(targetFullPath);
945 // Write the build rule.
946 this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
949 // Write the main driver rule to build everything in this target.
950 this->WriteTargetDriverRule(targetFullPath, relink);
952 // Clean all the possible library names and symlinks.
953 this->CleanFiles.insert(libCleanFiles.begin(), libCleanFiles.end());