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 // Clean files associated with this library.
291 std::set<std::string> libCleanFiles;
292 libCleanFiles.insert(
293 this->LocalGenerator->MaybeRelativeToCurBinDir(targetOutput));
295 // Determine whether a link script will be used.
296 bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
298 bool useResponseFileForObjects =
299 this->CheckUseResponseFileForObjects(linkLanguage);
300 bool const useResponseFileForLibs =
301 this->CheckUseResponseFileForLibraries(linkLanguage);
303 cmRulePlaceholderExpander::RuleVariables vars;
304 vars.Language = linkLanguage.c_str();
306 // Expand the rule variables.
307 std::vector<std::string> real_link_commands;
309 // Set path conversion for link script shells.
310 this->LocalGenerator->SetLinkScriptShell(useLinkScript);
312 // Collect up flags to link in needed libraries.
313 std::string linkLibs;
314 std::unique_ptr<cmLinkLineDeviceComputer> linkLineComputer(
315 new cmLinkLineDeviceComputer(
316 this->LocalGenerator,
317 this->LocalGenerator->GetStateSnapshot().GetDirectory()));
318 linkLineComputer->SetForResponse(useResponseFileForLibs);
319 linkLineComputer->SetRelink(relink);
321 // Create set of linking flags.
322 std::string linkFlags;
323 std::string ignored_;
324 this->LocalGenerator->GetDeviceLinkFlags(
325 *linkLineComputer, this->GetConfigName(), ignored_, linkFlags, ignored_,
326 ignored_, this->GeneratorTarget);
328 this->CreateLinkLibs(
329 linkLineComputer.get(), linkLibs, useResponseFileForLibs, depends,
330 cmMakefileTargetGenerator::ResponseFlagFor::DeviceLink);
332 // Construct object file lists that may be needed to expand the
334 std::string buildObjs;
335 this->CreateObjectLists(
336 useLinkScript, false, // useArchiveRules
337 useResponseFileForObjects, buildObjs, depends, false,
338 cmMakefileTargetGenerator::ResponseFlagFor::DeviceLink);
340 std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
341 objectDir = this->LocalGenerator->ConvertToOutputFormat(
342 this->LocalGenerator->MaybeRelativeToCurBinDir(objectDir),
343 cmOutputConverter::SHELL);
345 std::string target = this->LocalGenerator->ConvertToOutputFormat(
346 this->LocalGenerator->MaybeRelativeToCurBinDir(targetOutput),
347 cmOutputConverter::SHELL);
349 std::string targetFullPathCompilePDB =
350 this->ComputeTargetCompilePDB(this->GetConfigName());
351 std::string targetOutPathCompilePDB =
352 this->LocalGenerator->ConvertToOutputFormat(targetFullPathCompilePDB,
353 cmOutputConverter::SHELL);
355 vars.Objects = buildObjs.c_str();
356 vars.ObjectDir = objectDir.c_str();
357 vars.Target = target.c_str();
358 vars.LinkLibraries = linkLibs.c_str();
359 vars.ObjectsQuoted = buildObjs.c_str();
360 vars.LanguageCompileFlags = langFlags.c_str();
361 vars.LinkFlags = linkFlags.c_str();
362 vars.TargetCompilePDB = targetOutPathCompilePDB.c_str();
364 std::string launcher;
365 cmValue val = this->LocalGenerator->GetRuleLauncher(this->GeneratorTarget,
367 if (cmNonempty(val)) {
368 launcher = cmStrCat(*val, ' ');
371 std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
372 this->LocalGenerator->CreateRulePlaceholderExpander());
374 // Construct the main link rule and expand placeholders.
375 rulePlaceholderExpander->SetTargetImpLib(targetOutput);
376 std::string linkRule = this->GetLinkRule(linkRuleVar);
377 cmExpandList(linkRule, real_link_commands);
379 // Expand placeholders.
380 for (std::string& real_link_command : real_link_commands) {
381 real_link_command = cmStrCat(launcher, real_link_command);
382 rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
383 real_link_command, vars);
385 // Restore path conversion to normal shells.
386 this->LocalGenerator->SetLinkScriptShell(false);
388 // Clean all the possible library names and symlinks.
389 this->CleanFiles.insert(libCleanFiles.begin(), libCleanFiles.end());
392 std::vector<std::string> commands1;
393 // Optionally convert the build rule to use a script to avoid long
394 // command lines in the make shell.
396 // Use a link script.
397 const char* name = (relink ? "drelink.txt" : "dlink.txt");
398 this->CreateLinkScript(name, real_link_commands, commands1, depends);
400 // No link script. Just use the link rule directly.
401 commands1 = real_link_commands;
403 this->LocalGenerator->CreateCDCommand(
404 commands1, this->Makefile->GetCurrentBinaryDirectory(),
405 this->LocalGenerator->GetBinaryDirectory());
406 cm::append(commands, commands1);
409 // Compute the list of outputs.
410 std::vector<std::string> outputs(1, targetOutput);
412 // Write the build rule.
413 this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
416 static_cast<void>(linkRuleVar);
417 static_cast<void>(relink);
421 void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
422 const std::string& linkRuleVar, const std::string& extraFlags, bool relink)
424 // TODO: Merge the methods that call this method to avoid
426 std::vector<std::string> commands;
428 // Get the language to use for linking this library.
429 std::string linkLanguage =
430 this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
432 // Make sure we have a link language.
433 if (linkLanguage.empty()) {
434 cmSystemTools::Error("Cannot determine link language for target \"" +
435 this->GeneratorTarget->GetName() + "\".");
439 // Build list of dependencies.
440 std::vector<std::string> depends;
441 this->AppendLinkDepends(depends, linkLanguage);
442 if (!this->DeviceLinkObject.empty()) {
443 depends.push_back(this->DeviceLinkObject);
446 // Create set of linking flags.
447 std::string linkFlags;
448 this->LocalGenerator->AppendFlags(linkFlags, extraFlags);
449 this->LocalGenerator->AppendIPOLinkerFlags(
450 linkFlags, this->GeneratorTarget, this->GetConfigName(), linkLanguage);
452 // Add OSX version flags, if any.
453 if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
454 this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
455 this->AppendOSXVerFlag(linkFlags, linkLanguage, "COMPATIBILITY", true);
456 this->AppendOSXVerFlag(linkFlags, linkLanguage, "CURRENT", false);
459 // Construct the name of the library.
460 this->GeneratorTarget->GetLibraryNames(this->GetConfigName());
462 // Construct the full path version of the names.
464 std::string outpathImp;
465 if (this->GeneratorTarget->IsFrameworkOnApple()) {
466 outpath = this->GeneratorTarget->GetDirectory(this->GetConfigName());
467 this->OSXBundleGenerator->CreateFramework(this->TargetNames.Output,
468 outpath, this->GetConfigName());
470 } else if (this->GeneratorTarget->IsCFBundleOnApple()) {
471 outpath = this->GeneratorTarget->GetDirectory(this->GetConfigName());
472 this->OSXBundleGenerator->CreateCFBundle(this->TargetNames.Output, outpath,
473 this->GetConfigName());
476 outpath = cmStrCat(this->Makefile->GetCurrentBinaryDirectory(),
477 "/CMakeFiles/CMakeRelink.dir");
478 cmSystemTools::MakeDirectory(outpath);
480 if (!this->TargetNames.ImportLibrary.empty()) {
481 outpathImp = outpath;
484 outpath = this->GeneratorTarget->GetDirectory(this->GetConfigName());
485 cmSystemTools::MakeDirectory(outpath);
487 if (!this->TargetNames.ImportLibrary.empty()) {
488 outpathImp = this->GeneratorTarget->GetDirectory(
489 this->GetConfigName(), cmStateEnums::ImportLibraryArtifact);
490 cmSystemTools::MakeDirectory(outpathImp);
495 std::string compilePdbOutputPath =
496 this->GeneratorTarget->GetCompilePDBDirectory(this->GetConfigName());
497 cmSystemTools::MakeDirectory(compilePdbOutputPath);
499 std::string pdbOutputPath =
500 this->GeneratorTarget->GetPDBDirectory(this->GetConfigName());
501 cmSystemTools::MakeDirectory(pdbOutputPath);
502 pdbOutputPath += "/";
504 std::string targetFullPath = outpath + this->TargetNames.Output;
505 std::string targetFullPathPDB = pdbOutputPath + this->TargetNames.PDB;
506 std::string targetFullPathSO = outpath + this->TargetNames.SharedObject;
507 std::string targetFullPathReal = outpath + this->TargetNames.Real;
508 std::string targetFullPathImport =
509 outpathImp + this->TargetNames.ImportLibrary;
511 // Construct the output path version of the names for use in command
513 std::string targetOutPathPDB = this->LocalGenerator->ConvertToOutputFormat(
514 targetFullPathPDB, cmOutputConverter::SHELL);
516 std::string targetOutPath = this->LocalGenerator->ConvertToOutputFormat(
517 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPath),
518 cmOutputConverter::SHELL);
519 std::string targetOutPathSO = this->LocalGenerator->ConvertToOutputFormat(
520 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathSO),
521 cmOutputConverter::SHELL);
522 std::string targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
523 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathReal),
524 cmOutputConverter::SHELL);
525 std::string targetOutPathImport =
526 this->LocalGenerator->ConvertToOutputFormat(
527 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathImport),
528 cmOutputConverter::SHELL);
530 this->NumberOfProgressActions++;
531 if (!this->NoRuleMessages) {
532 cmLocalUnixMakefileGenerator3::EchoProgress progress;
533 this->MakeEchoProgress(progress);
534 // Add the link message.
535 std::string buildEcho = cmStrCat("Linking ", linkLanguage);
536 switch (this->GeneratorTarget->GetType()) {
537 case cmStateEnums::STATIC_LIBRARY:
538 buildEcho += " static library ";
540 case cmStateEnums::SHARED_LIBRARY:
541 buildEcho += " shared library ";
543 case cmStateEnums::MODULE_LIBRARY:
544 if (this->GeneratorTarget->IsCFBundleOnApple()) {
545 buildEcho += " CFBundle";
547 buildEcho += " shared module ";
550 buildEcho += " library ";
553 buildEcho += targetOutPath;
554 this->LocalGenerator->AppendEcho(
555 commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
558 // Clean files associated with this library.
559 std::set<std::string> libCleanFiles;
560 libCleanFiles.insert(
561 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathReal));
563 std::vector<std::string> commands1;
564 // Add a command to remove any existing files for this library.
565 // for static libs only
566 if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
567 this->LocalGenerator->AppendCleanCommand(commands1, libCleanFiles,
568 this->GeneratorTarget, "target");
569 this->LocalGenerator->CreateCDCommand(
570 commands1, this->Makefile->GetCurrentBinaryDirectory(),
571 this->LocalGenerator->GetBinaryDirectory());
572 cm::append(commands, commands1);
576 if (this->TargetNames.Output != this->TargetNames.Real) {
577 libCleanFiles.insert(
578 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPath));
580 if (this->TargetNames.SharedObject != this->TargetNames.Real &&
581 this->TargetNames.SharedObject != this->TargetNames.Output) {
582 libCleanFiles.insert(
583 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathSO));
585 if (!this->TargetNames.ImportLibrary.empty()) {
586 libCleanFiles.insert(
587 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathImport));
589 if (this->GeneratorTarget->GetImplibGNUtoMS(
590 this->GetConfigName(), targetFullPathImport, implib)) {
591 libCleanFiles.insert(
592 this->LocalGenerator->MaybeRelativeToCurBinDir(implib));
596 // List the PDB for cleaning only when the whole target is
597 // cleaned. We do not want to delete the .pdb file just before
598 // linking the target.
599 this->CleanFiles.insert(
600 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathPDB));
603 // There may be a manifest file for this target. Add it to the
604 // clean set just in case.
605 if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
606 libCleanFiles.insert(this->LocalGenerator->MaybeRelativeToCurBinDir(
607 targetFullPath + ".manifest"));
611 // Add the pre-build and pre-link rules building but not when relinking.
613 this->LocalGenerator->AppendCustomCommands(
614 commands, this->GeneratorTarget->GetPreBuildCommands(),
615 this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
616 this->LocalGenerator->AppendCustomCommands(
617 commands, this->GeneratorTarget->GetPreLinkCommands(),
618 this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
621 // Determine whether a link script will be used.
622 bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
624 bool useResponseFileForObjects =
625 this->CheckUseResponseFileForObjects(linkLanguage);
626 bool const useResponseFileForLibs =
627 this->CheckUseResponseFileForLibraries(linkLanguage);
629 // For static libraries there might be archiving rules.
630 bool haveStaticLibraryRule = false;
631 std::vector<std::string> archiveCreateCommands;
632 std::vector<std::string> archiveAppendCommands;
633 std::vector<std::string> archiveFinishCommands;
634 std::string::size_type archiveCommandLimit = std::string::npos;
635 if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
636 haveStaticLibraryRule = this->Makefile->IsDefinitionSet(linkRuleVar);
637 std::string arCreateVar =
638 cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_CREATE");
640 arCreateVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
641 arCreateVar, linkLanguage, this->GetConfigName());
643 this->Makefile->GetDefExpandList(arCreateVar, archiveCreateCommands);
644 std::string arAppendVar =
645 cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_APPEND");
647 arAppendVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
648 arAppendVar, linkLanguage, this->GetConfigName());
650 this->Makefile->GetDefExpandList(arAppendVar, archiveAppendCommands);
651 std::string arFinishVar =
652 cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_FINISH");
654 arFinishVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
655 arFinishVar, linkLanguage, this->GetConfigName());
657 this->Makefile->GetDefExpandList(arFinishVar, archiveFinishCommands);
660 // Decide whether to use archiving rules.
661 bool useArchiveRules = !haveStaticLibraryRule &&
662 !archiveCreateCommands.empty() && !archiveAppendCommands.empty();
663 if (useArchiveRules) {
664 // Archiving rules are always run with a link script.
665 useLinkScript = true;
667 // Archiving rules never use a response file.
668 useResponseFileForObjects = false;
670 // Limit the length of individual object lists to less than half of
671 // the command line length limit (leaving half for other flags).
672 // This may result in several calls to the archiver.
673 if (size_t limit = cmSystemTools::CalculateCommandLineLengthLimit()) {
674 archiveCommandLimit = limit / 2;
676 archiveCommandLimit = 8000;
680 // Expand the rule variables.
681 std::vector<std::string> real_link_commands;
683 bool useWatcomQuote =
684 this->Makefile->IsOn(linkRuleVar + "_USE_WATCOM_QUOTE");
686 // Set path conversion for link script shells.
687 this->LocalGenerator->SetLinkScriptShell(useLinkScript);
689 // Collect up flags to link in needed libraries.
690 std::string linkLibs;
691 if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
693 std::unique_ptr<cmLinkLineComputer> linkLineComputer =
694 this->CreateLinkLineComputer(
695 this->LocalGenerator,
696 this->LocalGenerator->GetStateSnapshot().GetDirectory());
697 linkLineComputer->SetForResponse(useResponseFileForLibs);
698 linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
699 linkLineComputer->SetRelink(relink);
701 this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
702 useResponseFileForLibs, depends);
705 // Construct object file lists that may be needed to expand the
707 std::string buildObjs;
708 this->CreateObjectLists(useLinkScript, useArchiveRules,
709 useResponseFileForObjects, buildObjs, depends,
711 if (!this->DeviceLinkObject.empty()) {
713 this->LocalGenerator->ConvertToOutputFormat(
714 this->LocalGenerator->MaybeRelativeToCurBinDir(
715 this->DeviceLinkObject),
716 cmOutputConverter::SHELL);
719 std::string const& aixExports = this->GetAIXExports(this->GetConfigName());
721 // maybe create .def file from list of objects
722 this->GenDefFile(real_link_commands);
724 std::string manifests = this->GetManifests(this->GetConfigName());
726 cmRulePlaceholderExpander::RuleVariables vars;
727 vars.TargetPDB = targetOutPathPDB.c_str();
729 // Setup the target version.
730 std::string targetVersionMajor;
731 std::string targetVersionMinor;
733 std::ostringstream majorStream;
734 std::ostringstream minorStream;
737 this->GeneratorTarget->GetTargetVersion(major, minor);
738 majorStream << major;
739 minorStream << minor;
740 targetVersionMajor = majorStream.str();
741 targetVersionMinor = minorStream.str();
743 vars.TargetVersionMajor = targetVersionMajor.c_str();
744 vars.TargetVersionMinor = targetVersionMinor.c_str();
746 vars.CMTargetName = this->GeneratorTarget->GetName().c_str();
748 cmState::GetTargetTypeName(this->GeneratorTarget->GetType()).c_str();
749 vars.Language = linkLanguage.c_str();
750 vars.AIXExports = aixExports.c_str();
751 vars.Objects = buildObjs.c_str();
752 std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
754 objectDir = this->LocalGenerator->ConvertToOutputFormat(
755 this->LocalGenerator->MaybeRelativeToCurBinDir(objectDir),
756 cmOutputConverter::SHELL);
758 vars.ObjectDir = objectDir.c_str();
759 cmOutputConverter::OutputFormat output = (useWatcomQuote)
760 ? cmOutputConverter::WATCOMQUOTE
761 : cmOutputConverter::SHELL;
762 std::string target = this->LocalGenerator->ConvertToOutputFormat(
763 this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathReal),
765 vars.Target = target.c_str();
766 vars.LinkLibraries = linkLibs.c_str();
767 vars.ObjectsQuoted = buildObjs.c_str();
768 std::string targetOutSOName;
769 if (this->GeneratorTarget->HasSOName(this->GetConfigName())) {
770 vars.SONameFlag = this->Makefile->GetSONameFlag(linkLanguage);
771 targetOutSOName = this->LocalGenerator->ConvertToOutputFormat(
772 this->TargetNames.SharedObject.c_str(), cmOutputConverter::SHELL);
773 vars.TargetSOName = targetOutSOName.c_str();
775 vars.LinkFlags = linkFlags.c_str();
777 vars.Manifests = manifests.c_str();
779 // Compute the directory portion of the install_name setting.
780 std::string install_name_dir;
781 if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY) {
782 // Get the install_name directory for the build tree.
783 install_name_dir = this->GeneratorTarget->GetInstallNameDirForBuildTree(
784 this->GetConfigName());
786 // Set the rule variable replacement value.
787 if (install_name_dir.empty()) {
788 vars.TargetInstallNameDir = "";
790 // Convert to a path for the native build tool.
791 install_name_dir = this->LocalGenerator->ConvertToOutputFormat(
792 install_name_dir, cmOutputConverter::SHELL);
793 vars.TargetInstallNameDir = install_name_dir.c_str();
797 // Add language-specific flags.
798 std::string langFlags;
799 this->LocalGenerator->AddLanguageFlagsForLinking(
800 langFlags, this->GeneratorTarget, linkLanguage, this->GetConfigName());
802 this->LocalGenerator->AddArchitectureFlags(
803 langFlags, this->GeneratorTarget, linkLanguage, this->GetConfigName());
805 vars.LanguageCompileFlags = langFlags.c_str();
807 std::string linkerLauncher =
808 this->GetLinkerLauncher(this->GetConfigName());
809 if (cmNonempty(linkerLauncher)) {
810 vars.Launcher = linkerLauncher.c_str();
813 std::string launcher;
814 cmValue val = this->LocalGenerator->GetRuleLauncher(this->GeneratorTarget,
816 if (cmNonempty(val)) {
817 launcher = cmStrCat(*val, ' ');
820 std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
821 this->LocalGenerator->CreateRulePlaceholderExpander());
822 // Construct the main link rule and expand placeholders.
823 rulePlaceholderExpander->SetTargetImpLib(targetOutPathImport);
824 if (useArchiveRules) {
825 // Construct the individual object list strings.
826 std::vector<std::string> object_strings;
827 this->WriteObjectsStrings(object_strings, archiveCommandLimit);
829 // Add the cuda device object to the list of archive files. This will
830 // only occur on archives which have CUDA_RESOLVE_DEVICE_SYMBOLS enabled
831 if (!this->DeviceLinkObject.empty()) {
832 object_strings.push_back(this->LocalGenerator->ConvertToOutputFormat(
833 this->LocalGenerator->MaybeRelativeToCurBinDir(
834 this->DeviceLinkObject),
835 cmOutputConverter::SHELL));
838 // Create the archive with the first set of objects.
839 auto osi = object_strings.begin();
841 vars.Objects = osi->c_str();
842 for (std::string const& acc : archiveCreateCommands) {
843 std::string cmd = launcher + acc;
844 rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
846 real_link_commands.push_back(std::move(cmd));
849 // Append to the archive with the other object sets.
850 for (++osi; osi != object_strings.end(); ++osi) {
851 vars.Objects = osi->c_str();
852 for (std::string const& aac : archiveAppendCommands) {
853 std::string cmd = launcher + aac;
854 rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
856 real_link_commands.push_back(std::move(cmd));
859 // Finish the archive.
861 for (std::string const& afc : archiveFinishCommands) {
862 std::string cmd = launcher + afc;
863 rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, cmd,
865 // If there is no ranlib the command will be ":". Skip it.
866 if (!cmd.empty() && cmd[0] != ':') {
867 real_link_commands.push_back(std::move(cmd));
871 // Get the set of commands.
872 std::string linkRule = this->GetLinkRule(linkRuleVar);
873 cmExpandList(linkRule, real_link_commands);
876 this->Makefile->GetDefinition("CMAKE_LINK_WHAT_YOU_USE_CHECK");
878 std::string cmakeCommand = cmStrCat(
879 this->LocalGenerator->ConvertToOutputFormat(
880 cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL),
881 " -E __run_co_compile --lwyu=");
882 cmakeCommand += this->LocalGenerator->EscapeForShell(*lwyuCheck);
883 cmakeCommand += cmStrCat(" --source=", targetOutPathReal);
884 real_link_commands.push_back(std::move(cmakeCommand));
888 // Expand placeholders.
889 for (std::string& real_link_command : real_link_commands) {
890 real_link_command = cmStrCat(launcher, real_link_command);
891 rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
892 real_link_command, vars);
896 // Restore path conversion to normal shells.
897 this->LocalGenerator->SetLinkScriptShell(false);
900 // Optionally convert the build rule to use a script to avoid long
901 // command lines in the make shell.
903 // Use a link script.
904 const char* name = (relink ? "relink.txt" : "link.txt");
905 this->CreateLinkScript(name, real_link_commands, commands1, depends);
907 // No link script. Just use the link rule directly.
908 commands1 = real_link_commands;
910 this->LocalGenerator->CreateCDCommand(
911 commands1, this->Makefile->GetCurrentBinaryDirectory(),
912 this->LocalGenerator->GetBinaryDirectory());
913 cm::append(commands, commands1);
916 // Add a rule to create necessary symlinks for the library.
917 // Frameworks are handled by cmOSXBundleGenerator.
918 if (targetOutPath != targetOutPathReal &&
919 !this->GeneratorTarget->IsFrameworkOnApple()) {
920 std::string symlink =
921 cmStrCat("$(CMAKE_COMMAND) -E cmake_symlink_library ", targetOutPathReal,
922 ' ', targetOutPathSO, ' ', targetOutPath);
923 commands1.push_back(std::move(symlink));
924 this->LocalGenerator->CreateCDCommand(
925 commands1, this->Makefile->GetCurrentBinaryDirectory(),
926 this->LocalGenerator->GetBinaryDirectory());
927 cm::append(commands, commands1);
931 // Add the post-build rules when building but not when relinking.
933 this->LocalGenerator->AppendCustomCommands(
934 commands, this->GeneratorTarget->GetPostBuildCommands(),
935 this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
938 // Compute the list of outputs.
939 std::vector<std::string> outputs;
941 outputs.push_back(targetFullPathReal);
942 if (this->TargetNames.SharedObject != this->TargetNames.Real) {
943 outputs.push_back(targetFullPathSO);
945 if (this->TargetNames.Output != this->TargetNames.SharedObject &&
946 this->TargetNames.Output != this->TargetNames.Real) {
947 outputs.push_back(targetFullPath);
950 // Write the build rule.
951 this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
954 // Write the main driver rule to build everything in this target.
955 this->WriteTargetDriverRule(targetFullPath, relink);
957 // Clean all the possible library names and symlinks.
958 this->CleanFiles.insert(libCleanFiles.begin(), libCleanFiles.end());