Merge branch 'release-3.29'
[kiteware-cmake.git] / Source / cmLocalUnixMakefileGenerator3.cxx
blob7def1fe15c24093fd92b92d160503565922d38ed
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 "cmLocalUnixMakefileGenerator3.h"
5 #include <algorithm>
6 #include <cassert>
7 #include <cstdio>
8 #include <functional>
9 #include <sstream>
10 #include <utility>
12 #include <cm/memory>
13 #include <cm/optional>
14 #include <cm/string_view>
15 #include <cm/vector>
16 #include <cmext/algorithm>
17 #include <cmext/string_view>
19 #include "cmsys/FStream.hxx"
20 #include "cmsys/Terminal.h"
22 #include "cmCMakePath.h"
23 #include "cmCustomCommand.h" // IWYU pragma: keep
24 #include "cmCustomCommandGenerator.h"
25 #include "cmDependsCompiler.h"
26 #include "cmFileTimeCache.h"
27 #include "cmGeneratedFileStream.h"
28 #include "cmGeneratorExpression.h"
29 #include "cmGeneratorTarget.h"
30 #include "cmGlobalGenerator.h"
31 #include "cmGlobalUnixMakefileGenerator3.h"
32 #include "cmList.h"
33 #include "cmListFileCache.h"
34 #include "cmLocalGenerator.h"
35 #include "cmMakefile.h"
36 #include "cmMakefileTargetGenerator.h"
37 #include "cmOutputConverter.h"
38 #include "cmRange.h"
39 #include "cmRulePlaceholderExpander.h"
40 #include "cmSourceFile.h"
41 #include "cmState.h"
42 #include "cmStateSnapshot.h"
43 #include "cmStateTypes.h"
44 #include "cmStringAlgorithms.h"
45 #include "cmSystemTools.h"
46 #include "cmTargetDepend.h"
47 #include "cmValue.h"
48 #include "cmVersion.h"
49 #include "cmake.h"
51 // Include dependency scanners for supported languages. Only the
52 // C/C++ scanner is needed for bootstrapping CMake.
53 #include "cmDependsC.h"
54 #ifndef CMAKE_BOOTSTRAP
55 # include "cmDependsFortran.h"
56 # include "cmDependsJava.h"
57 #endif
59 namespace {
60 // Helper function used below.
61 std::string cmSplitExtension(std::string const& in, std::string& base)
63 std::string ext;
64 std::string::size_type dot_pos = in.rfind('.');
65 if (dot_pos != std::string::npos) {
66 // Remove the extension first in case &base == &in.
67 ext = in.substr(dot_pos);
68 base = in.substr(0, dot_pos);
69 } else {
70 base = in;
72 return ext;
75 // Helper predicate for removing absolute paths that don't point to the
76 // source or binary directory. It is used when CMAKE_DEPENDS_IN_PROJECT_ONLY
77 // is set ON, to only consider in-project dependencies during the build.
78 class NotInProjectDir
80 public:
81 // Constructor with the source and binary directory's path
82 NotInProjectDir(cm::string_view sourceDir, cm::string_view binaryDir)
83 : SourceDir(sourceDir)
84 , BinaryDir(binaryDir)
88 // Operator evaluating the predicate
89 bool operator()(const std::string& p) const
91 auto path = cmCMakePath(p).Normal();
93 // Keep all relative paths:
94 if (path.IsRelative()) {
95 return false;
98 // If it's an absolute path, check if it starts with the source
99 // directory:
100 return !(cmCMakePath(this->SourceDir).IsPrefix(path) ||
101 cmCMakePath(this->BinaryDir).IsPrefix(path));
104 private:
105 // The path to the source directory
106 cm::string_view SourceDir;
107 // The path to the binary directory
108 cm::string_view BinaryDir;
112 cmLocalUnixMakefileGenerator3::cmLocalUnixMakefileGenerator3(
113 cmGlobalGenerator* gg, cmMakefile* mf)
114 : cmLocalCommonGenerator(gg, mf)
116 this->MakefileVariableSize = 0;
117 this->ColorMakefile = false;
118 this->SkipPreprocessedSourceRules = false;
119 this->SkipAssemblySourceRules = false;
120 this->MakeCommandEscapeTargetTwice = false;
121 this->BorlandMakeCurlyHack = false;
124 cmLocalUnixMakefileGenerator3::~cmLocalUnixMakefileGenerator3() = default;
126 std::string cmLocalUnixMakefileGenerator3::GetConfigName() const
128 auto const& configNames = this->GetConfigNames();
129 assert(configNames.size() == 1);
130 return configNames.front();
133 void cmLocalUnixMakefileGenerator3::Generate()
135 // Record whether some options are enabled to avoid checking many
136 // times later.
137 if (!this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
138 if (this->Makefile->IsSet("CMAKE_COLOR_MAKEFILE")) {
139 this->ColorMakefile = this->Makefile->IsOn("CMAKE_COLOR_MAKEFILE");
140 } else {
141 this->ColorMakefile = this->Makefile->IsOn("CMAKE_COLOR_DIAGNOSTICS");
144 this->SkipPreprocessedSourceRules =
145 this->Makefile->IsOn("CMAKE_SKIP_PREPROCESSED_SOURCE_RULES");
146 this->SkipAssemblySourceRules =
147 this->Makefile->IsOn("CMAKE_SKIP_ASSEMBLY_SOURCE_RULES");
149 // Generate the rule files for each target.
150 cmGlobalUnixMakefileGenerator3* gg =
151 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
152 for (cmGeneratorTarget* gt :
153 this->GlobalGenerator->GetLocalGeneratorTargetsInOrder(this)) {
154 if (!gt->IsInBuildSystem()) {
155 continue;
158 auto& gtVisited = this->GetCommandsVisited(gt);
159 const auto& deps = this->GlobalGenerator->GetTargetDirectDepends(gt);
160 for (const auto& d : deps) {
161 // Take the union of visited source files of custom commands
162 auto depVisited = this->GetCommandsVisited(d);
163 gtVisited.insert(depVisited.begin(), depVisited.end());
166 std::unique_ptr<cmMakefileTargetGenerator> tg(
167 cmMakefileTargetGenerator::New(gt));
168 if (tg) {
169 tg->WriteRuleFiles();
170 gg->RecordTargetProgress(tg.get());
174 // write the local Makefile
175 this->WriteLocalMakefile();
177 // Write the cmake file with information for this directory.
178 this->WriteDirectoryInformationFile();
181 void cmLocalUnixMakefileGenerator3::ComputeHomeRelativeOutputPath()
183 // Compute the path to use when referencing the current output
184 // directory from the top output directory.
185 this->HomeRelativeOutputPath =
186 this->MaybeRelativeToTopBinDir(this->GetCurrentBinaryDirectory());
187 if (this->HomeRelativeOutputPath == ".") {
188 this->HomeRelativeOutputPath.clear();
190 if (!this->HomeRelativeOutputPath.empty()) {
191 this->HomeRelativeOutputPath += "/";
195 void cmLocalUnixMakefileGenerator3::GetLocalObjectFiles(
196 std::map<std::string, LocalObjectInfo>& localObjectFiles)
198 for (const auto& gt : this->GetGeneratorTargets()) {
199 if (!gt->CanCompileSources()) {
200 continue;
202 std::vector<cmSourceFile const*> objectSources;
203 gt->GetObjectSources(objectSources, this->GetConfigName());
204 // Compute full path to object file directory for this target.
205 std::string dir = cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(),
206 '/', this->GetTargetDirectory(gt.get()), '/');
207 // Compute the name of each object file.
208 for (cmSourceFile const* sf : objectSources) {
209 bool hasSourceExtension = true;
210 std::string objectName =
211 this->GetObjectFileNameWithoutTarget(*sf, dir, &hasSourceExtension);
212 if (cmSystemTools::FileIsFullPath(objectName)) {
213 objectName = cmSystemTools::GetFilenameName(objectName);
215 LocalObjectInfo& info = localObjectFiles[objectName];
216 info.HasSourceExtension = hasSourceExtension;
217 info.emplace_back(gt.get(), sf->GetLanguage());
222 void cmLocalUnixMakefileGenerator3::GetIndividualFileTargets(
223 std::vector<std::string>& targets)
225 std::map<std::string, LocalObjectInfo> localObjectFiles;
226 this->GetLocalObjectFiles(localObjectFiles);
227 for (auto const& localObjectFile : localObjectFiles) {
228 targets.push_back(localObjectFile.first);
230 std::string::size_type dot_pos = localObjectFile.first.rfind(".");
231 std::string base = localObjectFile.first.substr(0, dot_pos);
232 if (localObjectFile.second.HasPreprocessRule) {
233 targets.push_back(base + ".i");
236 if (localObjectFile.second.HasAssembleRule) {
237 targets.push_back(base + ".s");
242 std::string cmLocalUnixMakefileGenerator3::GetLinkDependencyFile(
243 cmGeneratorTarget* target, std::string const& /*config*/) const
245 return cmStrCat(target->GetSupportDirectory(), "/link.d");
248 void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
250 // generate the includes
251 std::string ruleFileName = "Makefile";
253 // Open the rule file. This should be copy-if-different because the
254 // rules may depend on this file itself.
255 std::string ruleFileNameFull = this->ConvertToFullPath(ruleFileName);
256 cmGeneratedFileStream ruleFileStream(
257 ruleFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
258 if (!ruleFileStream) {
259 return;
261 // always write the top makefile
262 if (!this->IsRootMakefile()) {
263 ruleFileStream.SetCopyIfDifferent(true);
266 // write the all rules
267 this->WriteLocalAllRules(ruleFileStream);
269 // only write local targets unless at the top Keep track of targets already
270 // listed.
271 std::set<std::string> emittedTargets;
272 if (!this->IsRootMakefile()) {
273 // write our targets, and while doing it collect up the object
274 // file rules
275 this->WriteLocalMakefileTargets(ruleFileStream, emittedTargets);
276 } else {
277 cmGlobalUnixMakefileGenerator3* gg =
278 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
279 gg->WriteConvenienceRules(ruleFileStream, emittedTargets);
282 bool do_preprocess_rules = this->GetCreatePreprocessedSourceRules();
283 bool do_assembly_rules = this->GetCreateAssemblySourceRules();
285 std::map<std::string, LocalObjectInfo> localObjectFiles;
286 this->GetLocalObjectFiles(localObjectFiles);
288 // now write out the object rules
289 // for each object file name
290 for (auto& localObjectFile : localObjectFiles) {
291 // Add a convenience rule for building the object file.
292 this->WriteObjectConvenienceRule(
293 ruleFileStream, "target to build an object file", localObjectFile.first,
294 localObjectFile.second);
296 // Check whether preprocessing and assembly rules make sense.
297 // They make sense only for C and C++ sources.
298 bool lang_has_preprocessor = false;
299 bool lang_has_assembly = false;
301 for (LocalObjectEntry const& entry : localObjectFile.second) {
302 if (entry.Language == "C" || entry.Language == "CXX" ||
303 entry.Language == "CUDA" || entry.Language == "Fortran" ||
304 entry.Language == "HIP" || entry.Language == "ISPC") {
305 // Right now, C, C++, CUDA, Fortran, HIP and ISPC have both a
306 // preprocessor and the ability to generate assembly code
307 lang_has_preprocessor = true;
308 lang_has_assembly = true;
309 break;
313 // Add convenience rules for preprocessed and assembly files.
314 if (lang_has_preprocessor && do_preprocess_rules) {
315 std::string::size_type dot_pos = localObjectFile.first.rfind(".");
316 std::string base = localObjectFile.first.substr(0, dot_pos);
317 this->WriteObjectConvenienceRule(ruleFileStream,
318 "target to preprocess a source file",
319 (base + ".i"), localObjectFile.second);
320 localObjectFile.second.HasPreprocessRule = true;
323 if (lang_has_assembly && do_assembly_rules) {
324 std::string::size_type dot_pos = localObjectFile.first.rfind(".");
325 std::string base = localObjectFile.first.substr(0, dot_pos);
326 this->WriteObjectConvenienceRule(
327 ruleFileStream, "target to generate assembly for a file",
328 (base + ".s"), localObjectFile.second);
329 localObjectFile.second.HasAssembleRule = true;
333 // add a help target as long as there isn;t a real target named help
334 if (emittedTargets.insert("help").second) {
335 cmGlobalUnixMakefileGenerator3* gg =
336 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
337 gg->WriteHelpRule(ruleFileStream, this);
340 this->WriteSpecialTargetsBottom(ruleFileStream);
343 void cmLocalUnixMakefileGenerator3::WriteObjectConvenienceRule(
344 std::ostream& ruleFileStream, const char* comment, const std::string& output,
345 LocalObjectInfo const& info)
347 // If the rule includes the source file extension then create a
348 // version that has the extension removed. The help should include
349 // only the version without source extension.
350 bool inHelp = true;
351 if (info.HasSourceExtension) {
352 // Remove the last extension. This should be kept.
353 std::string outBase1 = output;
354 std::string outExt1 = cmSplitExtension(outBase1, outBase1);
356 // Now remove the source extension and put back the last
357 // extension.
358 std::string outNoExt;
359 cmSplitExtension(outBase1, outNoExt);
360 outNoExt += outExt1;
362 // Add a rule to drive the rule below.
363 std::vector<std::string> depends;
364 depends.emplace_back(output);
365 std::vector<std::string> no_commands;
366 this->WriteMakeRule(ruleFileStream, nullptr, outNoExt, depends,
367 no_commands, true, true);
368 inHelp = false;
371 // Recursively make the rule for each target using the object file.
372 std::vector<std::string> commands;
373 for (LocalObjectEntry const& t : info) {
374 std::string tgtMakefileName = this->GetRelativeTargetDirectory(t.Target);
375 std::string targetName = tgtMakefileName;
376 tgtMakefileName += "/build.make";
377 targetName += "/";
378 targetName += output;
379 commands.push_back(
380 this->GetRecursiveMakeCall(tgtMakefileName, targetName));
382 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
383 this->GetCurrentBinaryDirectory());
385 // Write the rule to the makefile.
386 std::vector<std::string> no_depends;
387 this->WriteMakeRule(ruleFileStream, comment, output, no_depends, commands,
388 true, inHelp);
391 void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
392 std::ostream& ruleFileStream, std::set<std::string>& emitted)
394 std::vector<std::string> depends;
395 std::vector<std::string> commands;
397 // for each target we just provide a rule to cd up to the top and do a make
398 // on the target
399 std::string localName;
400 for (const auto& target : this->GetGeneratorTargets()) {
401 if ((target->GetType() == cmStateEnums::EXECUTABLE) ||
402 (target->GetType() == cmStateEnums::STATIC_LIBRARY) ||
403 (target->GetType() == cmStateEnums::SHARED_LIBRARY) ||
404 (target->GetType() == cmStateEnums::MODULE_LIBRARY) ||
405 (target->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
406 (target->GetType() == cmStateEnums::UTILITY)) {
407 emitted.insert(target->GetName());
409 // for subdirs add a rule to build this specific target by name.
410 localName =
411 cmStrCat(this->GetRelativeTargetDirectory(target.get()), "/rule");
412 commands.clear();
413 depends.clear();
415 // Build the target for this pass.
416 std::string makefile2 = "CMakeFiles/Makefile2";
417 commands.push_back(this->GetRecursiveMakeCall(makefile2, localName));
418 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
419 this->GetCurrentBinaryDirectory());
420 this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
421 localName, depends, commands, true);
423 // Add a target with the canonical name (no prefix, suffix or path).
424 if (localName != target->GetName()) {
425 commands.clear();
426 depends.push_back(localName);
427 this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
428 target->GetName(), depends, commands, true);
431 // Add a fast rule to build the target
432 std::string makefileName = cmStrCat(
433 this->GetRelativeTargetDirectory(target.get()), "/build.make");
434 // make sure the makefile name is suitable for a makefile
435 std::string makeTargetName =
436 cmStrCat(this->GetRelativeTargetDirectory(target.get()), "/build");
437 localName = cmStrCat(target->GetName(), "/fast");
438 depends.clear();
439 commands.clear();
440 commands.push_back(
441 this->GetRecursiveMakeCall(makefileName, makeTargetName));
442 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
443 this->GetCurrentBinaryDirectory());
444 this->WriteMakeRule(ruleFileStream, "fast build rule for target.",
445 localName, depends, commands, true);
447 // Add a local name for the rule to relink the target before
448 // installation.
449 if (target->NeedRelinkBeforeInstall(this->GetConfigName())) {
450 makeTargetName = cmStrCat(
451 this->GetRelativeTargetDirectory(target.get()), "/preinstall");
452 localName = cmStrCat(target->GetName(), "/preinstall");
453 depends.clear();
454 commands.clear();
455 commands.push_back(
456 this->GetRecursiveMakeCall(makefile2, makeTargetName));
457 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
458 this->GetCurrentBinaryDirectory());
459 this->WriteMakeRule(ruleFileStream,
460 "Manual pre-install relink rule for target.",
461 localName, depends, commands, true);
467 void cmLocalUnixMakefileGenerator3::WriteDirectoryInformationFile()
469 std::string infoFileName =
470 cmStrCat(this->GetCurrentBinaryDirectory(),
471 "/CMakeFiles/CMakeDirectoryInformation.cmake");
473 // Open the output file.
474 cmGeneratedFileStream infoFileStream(infoFileName);
475 if (!infoFileStream) {
476 return;
479 infoFileStream.SetCopyIfDifferent(true);
480 // Write the do not edit header.
481 this->WriteDisclaimer(infoFileStream);
483 // Setup relative path conversion tops.
484 /* clang-format off */
485 infoFileStream
486 << "# Relative path conversion top directories.\n"
487 << "set(CMAKE_RELATIVE_PATH_TOP_SOURCE \""
488 << this->GetRelativePathTopSource() << "\")\n"
489 << "set(CMAKE_RELATIVE_PATH_TOP_BINARY \""
490 << this->GetRelativePathTopBinary() << "\")\n"
491 << "\n";
492 /* clang-format on */
494 // Tell the dependency scanner to use unix paths if necessary.
495 if (cmSystemTools::GetForceUnixPaths()) {
496 /* clang-format off */
497 infoFileStream
498 << "# Force unix paths in dependencies.\n"
499 << "set(CMAKE_FORCE_UNIX_PATHS 1)\n"
500 << "\n";
501 /* clang-format on */
504 // Store the include regular expressions for this directory.
505 infoFileStream << "\n"
506 << "# The C and CXX include file regular expressions for "
507 << "this directory.\n";
508 infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_SCAN ";
509 cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
510 infoFileStream, this->Makefile->GetIncludeRegularExpression());
511 infoFileStream << ")\n";
512 infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_COMPLAIN ";
513 cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
514 infoFileStream, this->Makefile->GetComplainRegularExpression());
515 infoFileStream << ")\n";
516 infoFileStream
517 << "set(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})\n";
518 infoFileStream << "set(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN "
519 "${CMAKE_C_INCLUDE_REGEX_COMPLAIN})\n";
522 std::string cmLocalUnixMakefileGenerator3::ConvertToFullPath(
523 const std::string& localPath)
525 std::string dir =
526 cmStrCat(this->GetCurrentBinaryDirectory(), '/', localPath);
527 return dir;
530 const std::string& cmLocalUnixMakefileGenerator3::GetHomeRelativeOutputPath()
532 return this->HomeRelativeOutputPath;
535 std::string cmLocalUnixMakefileGenerator3::ConvertToMakefilePath(
536 std::string const& path) const
538 cmGlobalUnixMakefileGenerator3* gg =
539 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
540 return gg->ConvertToMakefilePath(path);
543 void cmLocalUnixMakefileGenerator3::WriteMakeRule(
544 std::ostream& os, const char* comment, const std::string& target,
545 const std::vector<std::string>& depends,
546 const std::vector<std::string>& commands, bool symbolic, bool in_help)
548 // Make sure there is a target.
549 if (target.empty()) {
550 std::string err("No target for WriteMakeRule! called with comment: ");
551 if (comment) {
552 err += comment;
554 cmSystemTools::Error(err);
555 return;
558 std::string replace;
560 // Write the comment describing the rule in the makefile.
561 if (comment) {
562 replace = comment;
563 std::string::size_type lpos = 0;
564 std::string::size_type rpos;
565 while ((rpos = replace.find('\n', lpos)) != std::string::npos) {
566 os << "# " << replace.substr(lpos, rpos - lpos) << "\n";
567 lpos = rpos + 1;
569 os << "# " << replace.substr(lpos) << "\n";
572 // Construct the left hand side of the rule.
573 std::string tgt =
574 this->ConvertToMakefilePath(this->MaybeRelativeToTopBinDir(target));
576 const char* space = "";
577 if (tgt.size() == 1) {
578 // Add a space before the ":" to avoid drive letter confusion on
579 // Windows.
580 space = " ";
583 // Mark the rule as symbolic if requested.
584 if (symbolic) {
585 if (cmValue sym =
586 this->Makefile->GetDefinition("CMAKE_MAKE_SYMBOLIC_RULE")) {
587 os << tgt << space << ": " << *sym << "\n";
591 // Write the rule.
592 if (depends.empty()) {
593 // No dependencies. The commands will always run.
594 os << tgt << space << ":\n";
595 } else {
596 // Split dependencies into multiple rule lines. This allows for
597 // very long dependency lists even on older make implementations.
598 for (std::string const& depend : depends) {
599 os << tgt << space << ": "
600 << this->ConvertToMakefilePath(this->MaybeRelativeToTopBinDir(depend))
601 << '\n';
605 if (!commands.empty()) {
606 // Write the list of commands.
607 os << cmWrap("\t", commands, "", "\n") << "\n";
609 if (symbolic && !this->IsWatcomWMake()) {
610 os << ".PHONY : " << tgt << "\n";
612 os << "\n";
613 // Add the output to the local help if requested.
614 if (in_help) {
615 this->LocalHelp.push_back(target);
619 std::string cmLocalUnixMakefileGenerator3::MaybeConvertWatcomShellCommand(
620 std::string const& cmd)
622 if (this->IsWatcomWMake() && cmSystemTools::FileIsFullPath(cmd) &&
623 cmd.find_first_of("( )") != std::string::npos) {
624 // On Watcom WMake use the windows short path for the command
625 // name. This is needed to avoid funny quoting problems on
626 // lines with shell redirection operators.
627 std::string scmd;
628 if (cmSystemTools::GetShortPath(cmd, scmd)) {
629 return this->ConvertToOutputFormat(scmd, cmOutputConverter::SHELL);
632 return std::string();
635 void cmLocalUnixMakefileGenerator3::WriteMakeVariables(
636 std::ostream& makefileStream)
638 this->WriteDivider(makefileStream);
639 makefileStream << "# Set environment variables for the build.\n"
640 << "\n";
641 cmGlobalUnixMakefileGenerator3* gg =
642 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
643 if (gg->DefineWindowsNULL) {
644 makefileStream << "!IF \"$(OS)\" == \"Windows_NT\"\n"
645 << "NULL=\n"
646 << "!ELSE\n"
647 << "NULL=nul\n"
648 << "!ENDIF\n";
650 if (this->IsWindowsShell()) {
651 makefileStream << "SHELL = cmd.exe\n"
652 << "\n";
653 } else {
654 #if !defined(__VMS)
655 /* clang-format off */
656 makefileStream
657 << "# The shell in which to execute make rules.\n"
658 << "SHELL = /bin/sh\n"
659 << "\n";
660 /* clang-format on */
661 #endif
664 std::string cmakeShellCommand =
665 this->MaybeConvertWatcomShellCommand(cmSystemTools::GetCMakeCommand());
666 if (cmakeShellCommand.empty()) {
667 cmakeShellCommand = this->ConvertToOutputFormat(
668 cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
671 /* clang-format off */
672 makefileStream
673 << "# The CMake executable.\n"
674 << "CMAKE_COMMAND = "
675 << cmakeShellCommand
676 << "\n"
677 << "\n";
678 makefileStream
679 << "# The command to remove a file.\n"
680 << "RM = "
681 << cmakeShellCommand
682 << " -E rm -f\n"
683 << "\n";
684 makefileStream
685 << "# Escaping for special characters.\n"
686 << "EQUALS = =\n"
687 << "\n";
688 makefileStream
689 << "# The top-level source directory on which CMake was run.\n"
690 << "CMAKE_SOURCE_DIR = "
691 << this->ConvertToOutputFormat(
692 this->GetSourceDirectory(), cmOutputConverter::SHELL)
693 << "\n"
694 << "\n";
695 makefileStream
696 << "# The top-level build directory on which CMake was run.\n"
697 << "CMAKE_BINARY_DIR = "
698 << this->ConvertToOutputFormat(
699 this->GetBinaryDirectory(), cmOutputConverter::SHELL)
700 << "\n"
701 << "\n";
702 /* clang-format on */
705 void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsTop(
706 std::ostream& makefileStream)
708 this->WriteDivider(makefileStream);
709 makefileStream << "# Special targets provided by cmake.\n"
710 << "\n";
712 std::vector<std::string> no_commands;
713 std::vector<std::string> no_depends;
715 // Special target to cleanup operation of make tool.
716 // This should be the first target except for the default_target in
717 // the interface Makefile.
718 this->WriteMakeRule(makefileStream,
719 "Disable implicit rules so canonical targets will work.",
720 ".SUFFIXES", no_depends, no_commands, false);
722 if (!this->IsNMake() && !this->IsWatcomWMake() &&
723 !this->BorlandMakeCurlyHack) {
724 // turn off RCS and SCCS automatic stuff from gmake
725 constexpr const char* vcs_rules[] = {
726 "%,v", "RCS/%", "RCS/%,v", "SCCS/s.%", "s.%",
728 for (const auto* vcs_rule : vcs_rules) {
729 std::vector<std::string> vcs_depend;
730 vcs_depend.emplace_back(vcs_rule);
731 this->WriteMakeRule(makefileStream, "Disable VCS-based implicit rules.",
732 "%", vcs_depend, no_commands, false);
735 // Add a fake suffix to keep HP happy. Must be max 32 chars for SGI make.
736 std::vector<std::string> depends;
737 depends.emplace_back(".hpux_make_needs_suffix_list");
738 this->WriteMakeRule(makefileStream, nullptr, ".SUFFIXES", depends,
739 no_commands, false);
740 if (this->IsWatcomWMake()) {
741 // Switch on WMake feature, if an error or interrupt occurs during
742 // makefile processing, the current target being made may be deleted
743 // without prompting (the same as command line -e option).
744 /* clang-format off */
745 makefileStream <<
746 "\n"
747 ".ERASE\n"
748 "\n"
750 /* clang-format on */
752 if (this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE")) {
753 /* clang-format off */
754 makefileStream
755 << "# Produce verbose output by default.\n"
756 << "VERBOSE = 1\n"
757 << "\n";
758 /* clang-format on */
760 if (this->IsWatcomWMake()) {
761 /* clang-format off */
762 makefileStream <<
763 "!ifndef VERBOSE\n"
764 ".SILENT\n"
765 "!endif\n"
766 "\n"
768 /* clang-format on */
769 } else {
770 makefileStream << "# Command-line flag to silence nested $(MAKE).\n"
771 "$(VERBOSE)MAKESILENT = -s\n"
772 "\n";
774 // Write special target to silence make output. This must be after
775 // the default target in case VERBOSE is set (which changes the
776 // name). The setting of CMAKE_VERBOSE_MAKEFILE to ON will cause a
777 // "VERBOSE=1" to be added as a make variable which will change the
778 // name of this special target. This gives a make-time choice to
779 // the user.
780 // Write directly to the stream since WriteMakeRule escapes '$'.
781 makefileStream << "#Suppress display of executed commands.\n"
782 "$(VERBOSE).SILENT:\n"
783 "\n";
786 // Work-around for makes that drop rules that have no dependencies
787 // or commands.
788 cmGlobalUnixMakefileGenerator3* gg =
789 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
790 std::string hack = gg->GetEmptyRuleHackDepends();
791 if (!hack.empty()) {
792 no_depends.push_back(std::move(hack));
794 std::string hack_cmd = gg->GetEmptyRuleHackCommand();
795 if (!hack_cmd.empty()) {
796 no_commands.push_back(std::move(hack_cmd));
799 // Special symbolic target that never exists to force dependers to
800 // run their rules.
801 this->WriteMakeRule(makefileStream, "A target that is always out of date.",
802 "cmake_force", no_depends, no_commands, true);
804 // Variables for reference by other rules.
805 this->WriteMakeVariables(makefileStream);
808 void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom(
809 std::ostream& makefileStream)
811 this->WriteDivider(makefileStream);
812 makefileStream << "# Special targets to cleanup operation of make.\n"
813 << "\n";
815 // Write special "cmake_check_build_system" target to run cmake with
816 // the --check-build-system flag.
817 if (!this->GlobalGenerator->GlobalSettingIsOn(
818 "CMAKE_SUPPRESS_REGENERATION")) {
819 // Build command to run CMake to check if anything needs regenerating.
820 std::vector<std::string> commands;
821 cmake* cm = this->GlobalGenerator->GetCMakeInstance();
822 if (cm->DoWriteGlobVerifyTarget()) {
823 std::string rescanRule =
824 cmStrCat("$(CMAKE_COMMAND) -P ",
825 this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
826 cmOutputConverter::SHELL));
827 commands.push_back(rescanRule);
829 std::string cmakefileName = "CMakeFiles/Makefile.cmake";
830 std::string runRule = cmStrCat(
831 "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) ",
832 cm->GetIgnoreWarningAsError() ? "--compile-no-warning-as-error " : "",
833 "--check-build-system ",
834 this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
835 " 0");
837 std::vector<std::string> no_depends;
838 commands.push_back(std::move(runRule));
839 if (!this->IsRootMakefile()) {
840 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
841 this->GetCurrentBinaryDirectory());
843 this->WriteMakeRule(makefileStream,
844 "Special rule to run CMake to check the build system "
845 "integrity.\n"
846 "No rule that depends on this can have "
847 "commands that come from listfiles\n"
848 "because they might be regenerated.",
849 "cmake_check_build_system", no_depends, commands,
850 true);
854 void cmLocalUnixMakefileGenerator3::WriteConvenienceRule(
855 std::ostream& ruleFileStream, const std::string& realTarget,
856 const std::string& helpTarget)
858 // A rule is only needed if the names are different.
859 if (realTarget != helpTarget) {
860 // The helper target depends on the real target.
861 std::vector<std::string> depends;
862 depends.push_back(realTarget);
864 // There are no commands.
865 std::vector<std::string> no_commands;
867 // Write the rule.
868 this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
869 helpTarget, depends, no_commands, true);
873 std::string cmLocalUnixMakefileGenerator3::GetRelativeTargetDirectory(
874 cmGeneratorTarget const* target) const
876 std::string dir =
877 cmStrCat(this->HomeRelativeOutputPath, this->GetTargetDirectory(target));
878 return dir;
881 void cmLocalUnixMakefileGenerator3::AppendFlags(
882 std::string& flags, const std::string& newFlags) const
884 if (this->IsWatcomWMake() && !newFlags.empty()) {
885 std::string newf = newFlags;
886 if (newf.find("\\\"") != std::string::npos) {
887 cmSystemTools::ReplaceString(newf, "\\\"", "\"");
888 this->cmLocalGenerator::AppendFlags(flags, newf);
889 return;
892 this->cmLocalGenerator::AppendFlags(flags, newFlags);
895 void cmLocalUnixMakefileGenerator3::AppendRuleDepend(
896 std::vector<std::string>& depends, const char* ruleFileName)
898 // Add a dependency on the rule file itself unless an option to skip
899 // it is specifically enabled by the user or project.
900 cmValue nodep = this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY");
901 if (nodep.IsOff()) {
902 depends.emplace_back(ruleFileName);
906 void cmLocalUnixMakefileGenerator3::AppendRuleDepends(
907 std::vector<std::string>& depends, std::vector<std::string> const& ruleFiles)
909 // Add a dependency on the rule file itself unless an option to skip
910 // it is specifically enabled by the user or project.
911 if (!this->Makefile->IsOn("CMAKE_SKIP_RULE_DEPENDENCY")) {
912 cm::append(depends, ruleFiles);
916 void cmLocalUnixMakefileGenerator3::AppendCustomDepends(
917 std::vector<std::string>& depends, const std::vector<cmCustomCommand>& ccs)
919 for (cmCustomCommand const& cc : ccs) {
920 cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
921 this->AppendCustomDepend(depends, ccg);
925 void cmLocalUnixMakefileGenerator3::AppendCustomDepend(
926 std::vector<std::string>& depends, cmCustomCommandGenerator const& ccg)
928 for (std::string const& d : ccg.GetDepends()) {
929 // Lookup the real name of the dependency in case it is a CMake target.
930 std::string dep;
931 if (this->GetRealDependency(d, this->GetConfigName(), dep)) {
932 depends.push_back(std::move(dep));
937 void cmLocalUnixMakefileGenerator3::AppendCustomCommands(
938 std::vector<std::string>& commands, const std::vector<cmCustomCommand>& ccs,
939 cmGeneratorTarget* target, std::string const& relative)
941 for (cmCustomCommand const& cc : ccs) {
942 cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
943 this->AppendCustomCommand(commands, ccg, target, relative, true);
947 void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
948 std::vector<std::string>& commands, cmCustomCommandGenerator const& ccg,
949 cmGeneratorTarget* target, std::string const& relative, bool echo_comment,
950 std::ostream* content)
952 // Optionally create a command to display the custom command's
953 // comment text. This is used for pre-build, pre-link, and
954 // post-build command comments. Custom build step commands have
955 // their comments generated elsewhere.
956 if (echo_comment) {
957 if (cm::optional<std::string> comment = ccg.GetComment()) {
958 this->AppendEcho(commands, *comment,
959 cmLocalUnixMakefileGenerator3::EchoGenerate);
963 // if the command specified a working directory use it.
964 std::string dir = this->GetCurrentBinaryDirectory();
965 std::string workingDir = ccg.GetWorkingDirectory();
966 if (!workingDir.empty()) {
967 dir = workingDir;
969 if (content) {
970 *content << dir;
973 auto rulePlaceholderExpander = this->CreateRulePlaceholderExpander();
975 // Add each command line to the set of commands.
976 std::vector<std::string> commands1;
977 for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
978 // Build the command line in a single string.
979 std::string cmd = ccg.GetCommand(c);
980 if (!cmd.empty()) {
981 // Use "call " before any invocations of .bat or .cmd files
982 // invoked as custom commands in the WindowsShell.
984 bool useCall = false;
986 if (this->IsWindowsShell()) {
987 std::string suffix;
988 if (cmd.size() > 4) {
989 suffix = cmSystemTools::LowerCase(cmd.substr(cmd.size() - 4));
990 if (suffix == ".bat" || suffix == ".cmd") {
991 useCall = true;
996 cmSystemTools::ReplaceString(cmd, "/./", "/");
997 // Convert the command to a relative path only if the current
998 // working directory will be the start-output directory.
999 bool had_slash = cmd.find('/') != std::string::npos;
1000 if (workingDir.empty()) {
1001 cmd = this->MaybeRelativeToCurBinDir(cmd);
1003 bool has_slash = cmd.find('/') != std::string::npos;
1004 if (had_slash && !has_slash) {
1005 // This command was specified as a path to a file in the
1006 // current directory. Add a leading "./" so it can run
1007 // without the current directory being in the search path.
1008 cmd = cmStrCat("./", cmd);
1011 std::string launcher;
1012 // Short-circuit if there is no launcher.
1013 std::string val = this->GetRuleLauncher(
1014 target, "RULE_LAUNCH_CUSTOM",
1015 this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
1016 if (cmNonempty(val)) {
1017 // Expand rule variables referenced in the given launcher command.
1018 cmRulePlaceholderExpander::RuleVariables vars;
1019 vars.CMTargetName = target->GetName().c_str();
1020 vars.CMTargetType =
1021 cmState::GetTargetTypeName(target->GetType()).c_str();
1022 std::string output;
1023 const std::vector<std::string>& outputs = ccg.GetOutputs();
1024 if (!outputs.empty()) {
1025 output = outputs[0];
1026 if (workingDir.empty()) {
1027 output = this->MaybeRelativeToCurBinDir(output);
1029 output =
1030 this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
1032 vars.Output = output.c_str();
1034 launcher = val;
1035 rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
1036 if (!launcher.empty()) {
1037 launcher += " ";
1041 std::string shellCommand = this->MaybeConvertWatcomShellCommand(cmd);
1042 if (shellCommand.empty()) {
1043 shellCommand =
1044 this->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
1046 cmd = launcher + shellCommand;
1048 ccg.AppendArguments(c, cmd);
1049 if (content) {
1050 // Rule content does not include the launcher.
1051 *content << (cmd.c_str() + launcher.size());
1053 if (this->BorlandMakeCurlyHack) {
1054 // Borland Make has a very strange bug. If the first curly
1055 // brace anywhere in the command string is a left curly, it
1056 // must be written {{} instead of just {. Otherwise some
1057 // curly braces are removed. The hack can be skipped if the
1058 // first curly brace is the last character.
1059 std::string::size_type lcurly = cmd.find('{');
1060 if (lcurly != std::string::npos && lcurly < (cmd.size() - 1)) {
1061 std::string::size_type rcurly = cmd.find('}');
1062 if (rcurly == std::string::npos || rcurly > lcurly) {
1063 // The first curly is a left curly. Use the hack.
1064 cmd =
1065 cmStrCat(cmd.substr(0, lcurly), "{{}", cmd.substr(lcurly + 1));
1069 if (launcher.empty()) {
1070 if (useCall) {
1071 cmd = cmStrCat("call ", cmd);
1072 } else if (this->IsNMake() && cmd[0] == '"') {
1073 cmd = cmStrCat("echo >nul && ", cmd);
1076 commands1.push_back(std::move(cmd));
1080 // Setup the proper working directory for the commands.
1081 this->CreateCDCommand(commands1, dir, relative);
1083 cmGlobalUnixMakefileGenerator3* gg =
1084 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
1086 // Prefix the commands with the jobserver prefix "+"
1087 if (ccg.GetCC().GetJobserverAware() && gg->IsGNUMakeJobServerAware()) {
1088 std::transform(commands1.begin(), commands1.end(), commands1.begin(),
1089 [](std::string const& cmd) { return cmStrCat("+", cmd); });
1092 // push back the custom commands
1093 cm::append(commands, commands1);
1096 void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
1097 std::vector<std::string>& commands, const std::set<std::string>& files,
1098 cmGeneratorTarget* target, const char* filename)
1100 std::string currentBinDir = this->GetCurrentBinaryDirectory();
1101 std::string cleanfile = cmStrCat(
1102 currentBinDir, '/', this->GetTargetDirectory(target), "/cmake_clean");
1103 if (filename) {
1104 cleanfile += "_";
1105 cleanfile += filename;
1107 cleanfile += ".cmake";
1108 cmsys::ofstream fout(cleanfile.c_str());
1109 if (!fout) {
1110 cmSystemTools::Error("Could not create " + cleanfile);
1112 if (!files.empty()) {
1113 fout << "file(REMOVE_RECURSE\n";
1114 for (std::string const& file : files) {
1115 std::string fc = this->MaybeRelativeToCurBinDir(file);
1116 fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
1118 fout << ")\n";
1121 std::string remove = cmStrCat(
1122 "$(CMAKE_COMMAND) -P ",
1123 this->ConvertToOutputFormat(this->MaybeRelativeToCurBinDir(cleanfile),
1124 cmOutputConverter::SHELL));
1125 commands.push_back(std::move(remove));
1128 // For the main clean rule add per-language cleaning.
1129 if (!filename) {
1130 // Get the set of source languages in the target.
1131 std::set<std::string> languages;
1132 target->GetLanguages(
1133 languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
1134 /* clang-format off */
1135 fout << "\n"
1136 << "# Per-language clean rules from dependency scanning.\n"
1137 << "foreach(lang " << cmJoin(languages, " ") << ")\n"
1138 << " include(" << this->GetTargetDirectory(target)
1139 << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
1140 << "endforeach()\n";
1141 /* clang-format on */
1145 void cmLocalUnixMakefileGenerator3::AppendDirectoryCleanCommand(
1146 std::vector<std::string>& commands)
1148 cmList cleanFiles;
1149 // Look for additional files registered for cleaning in this directory.
1150 if (cmValue prop_value =
1151 this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
1152 cleanFiles.assign(cmGeneratorExpression::Evaluate(
1153 *prop_value, this,
1154 this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")));
1156 if (cleanFiles.empty()) {
1157 return;
1160 const auto& rootLG = this->GetGlobalGenerator()->GetLocalGenerators().at(0);
1161 std::string const& currentBinaryDir = this->GetCurrentBinaryDirectory();
1162 std::string cleanfile =
1163 cmStrCat(currentBinaryDir, "/CMakeFiles/cmake_directory_clean.cmake");
1164 // Write clean script
1166 cmsys::ofstream fout(cleanfile.c_str());
1167 if (!fout) {
1168 cmSystemTools::Error("Could not create " + cleanfile);
1169 return;
1171 fout << "file(REMOVE_RECURSE\n";
1172 for (std::string const& cfl : cleanFiles) {
1173 std::string fc = rootLG->MaybeRelativeToCurBinDir(
1174 cmSystemTools::CollapseFullPath(cfl, currentBinaryDir));
1175 fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
1177 fout << ")\n";
1179 // Create command
1181 std::string remove = cmStrCat(
1182 "$(CMAKE_COMMAND) -P ",
1183 this->ConvertToOutputFormat(rootLG->MaybeRelativeToCurBinDir(cleanfile),
1184 cmOutputConverter::SHELL));
1185 commands.push_back(std::move(remove));
1189 void cmLocalUnixMakefileGenerator3::AppendEcho(
1190 std::vector<std::string>& commands, std::string const& text, EchoColor color,
1191 EchoProgress const* progress)
1193 // Choose the color for the text.
1194 std::string color_name;
1195 if (this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile) {
1196 // See cmake::ExecuteEchoColor in cmake.cxx for these options.
1197 // This color set is readable on both black and white backgrounds.
1198 switch (color) {
1199 case EchoNormal:
1200 break;
1201 case EchoDepend:
1202 color_name = "--magenta --bold ";
1203 break;
1204 case EchoBuild:
1205 color_name = "--green ";
1206 break;
1207 case EchoLink:
1208 color_name = "--green --bold ";
1209 break;
1210 case EchoGenerate:
1211 color_name = "--blue --bold ";
1212 break;
1213 case EchoGlobal:
1214 color_name = "--cyan ";
1215 break;
1219 // Echo one line at a time.
1220 std::string line;
1221 line.reserve(200);
1222 for (const char* c = text.c_str();; ++c) {
1223 if (*c == '\n' || *c == '\0') {
1224 // Avoid writing a blank last line on end-of-string.
1225 if (*c != '\0' || !line.empty()) {
1226 // Add a command to echo this line.
1227 std::string cmd;
1228 if (color_name.empty() && !progress) {
1229 // Use the native echo command.
1230 cmd = cmStrCat("@echo ", this->EscapeForShell(line, false, true));
1231 } else {
1232 // Use cmake to echo the text in color.
1233 cmd = cmStrCat(
1234 "@$(CMAKE_COMMAND) -E cmake_echo_color \"--switch=$(COLOR)\" ",
1235 color_name);
1236 if (progress) {
1237 cmd += "--progress-dir=";
1238 cmd += this->ConvertToOutputFormat(progress->Dir,
1239 cmOutputConverter::SHELL);
1240 cmd += " ";
1241 cmd += "--progress-num=";
1242 cmd += progress->Arg;
1243 cmd += " ";
1245 cmd += this->EscapeForShell(line);
1247 commands.push_back(std::move(cmd));
1250 // Reset the line to empty.
1251 line.clear();
1253 // Progress appears only on first line.
1254 progress = nullptr;
1256 // Terminate on end-of-string.
1257 if (*c == '\0') {
1258 return;
1260 } else if (*c != '\r') {
1261 // Append this character to the current line.
1262 line += *c;
1267 std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
1268 std::string const& s, std::string const& s2)
1270 std::string unmodified = cmStrCat(s, s2);
1271 // if there is no restriction on the length of make variables
1272 // and there are no "." characters in the string, then return the
1273 // unmodified combination.
1274 if ((!this->MakefileVariableSize &&
1275 unmodified.find('.') == std::string::npos) &&
1276 (!this->MakefileVariableSize &&
1277 unmodified.find('+') == std::string::npos) &&
1278 (!this->MakefileVariableSize &&
1279 unmodified.find('-') == std::string::npos)) {
1280 return unmodified;
1283 // see if the variable has been defined before and return
1284 // the modified version of the variable
1285 auto i = this->MakeVariableMap.find(unmodified);
1286 if (i != this->MakeVariableMap.end()) {
1287 return i->second;
1289 // start with the unmodified variable
1290 std::string ret = unmodified;
1291 // if this there is no value for this->MakefileVariableSize then
1292 // the string must have bad characters in it
1293 if (!this->MakefileVariableSize) {
1294 std::replace(ret.begin(), ret.end(), '.', '_');
1295 cmSystemTools::ReplaceString(ret, "-", "__");
1296 cmSystemTools::ReplaceString(ret, "+", "___");
1297 int ni = 0;
1298 char buffer[12];
1299 // make sure the _ version is not already used, if
1300 // it is used then add number to the end of the variable
1301 while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
1302 ++ni;
1303 snprintf(buffer, sizeof(buffer), "%04d", ni);
1304 ret = unmodified + buffer;
1306 this->ShortMakeVariableMap[ret] = "1";
1307 this->MakeVariableMap[unmodified] = ret;
1308 return ret;
1311 // if the string is greater than 32 chars it is an invalid variable name
1312 // for borland make
1313 if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
1314 int keep = this->MakefileVariableSize - 8;
1315 int size = keep + 3;
1316 std::string str1 = s;
1317 std::string str2 = s2;
1318 // we must shorten the combined string by 4 characters
1319 // keep no more than 24 characters from the second string
1320 if (static_cast<int>(str2.size()) > keep) {
1321 str2 = str2.substr(0, keep);
1323 if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
1324 str1 = str1.substr(0, size - str2.size());
1326 char buffer[12];
1327 int ni = 0;
1328 snprintf(buffer, sizeof(buffer), "%04d", ni);
1329 ret = str1 + str2 + buffer;
1330 while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
1331 ++ni;
1332 snprintf(buffer, sizeof(buffer), "%04d", ni);
1333 ret = str1 + str2 + buffer;
1335 if (ni == 1000) {
1336 cmSystemTools::Error("Borland makefile variable length too long");
1337 return unmodified;
1339 // once an unused variable is found
1340 this->ShortMakeVariableMap[ret] = "1";
1342 // always make an entry into the unmodified to variable map
1343 this->MakeVariableMap[unmodified] = ret;
1344 return ret;
1347 bool cmLocalUnixMakefileGenerator3::UpdateDependencies(
1348 const std::string& tgtInfo, bool verbose, bool color)
1350 // read in the target info file
1351 if (!this->Makefile->ReadListFile(tgtInfo) ||
1352 cmSystemTools::GetErrorOccurredFlag()) {
1353 cmSystemTools::Error("Target DependInfo.cmake file not found");
1356 bool status = true;
1358 // Check if any multiple output pairs have a missing file.
1359 this->CheckMultipleOutputs(verbose);
1361 std::string const targetDir = cmSystemTools::GetFilenamePath(tgtInfo);
1362 if (!this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES").empty()) {
1363 // dependencies are managed by CMake itself
1365 std::string const internalDependFile = targetDir + "/depend.internal";
1366 std::string const dependFile = targetDir + "/depend.make";
1368 // If the target DependInfo.cmake file has changed since the last
1369 // time dependencies were scanned then force rescanning. This may
1370 // happen when a new source file is added and CMake regenerates the
1371 // project but no other sources were touched.
1372 bool needRescanDependInfo = false;
1373 cmFileTimeCache* ftc =
1374 this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache();
1376 int result;
1377 if (!ftc->Compare(internalDependFile, tgtInfo, &result) || result < 0) {
1378 if (verbose) {
1379 cmSystemTools::Stdout(cmStrCat("Dependee \"", tgtInfo,
1380 "\" is newer than depender \"",
1381 internalDependFile, "\".\n"));
1383 needRescanDependInfo = true;
1387 // If the directory information is newer than depend.internal, include
1388 // dirs may have changed. In this case discard all old dependencies.
1389 bool needRescanDirInfo = false;
1391 std::string dirInfoFile =
1392 cmStrCat(this->GetCurrentBinaryDirectory(),
1393 "/CMakeFiles/CMakeDirectoryInformation.cmake");
1394 int result;
1395 if (!ftc->Compare(internalDependFile, dirInfoFile, &result) ||
1396 result < 0) {
1397 if (verbose) {
1398 cmSystemTools::Stdout(cmStrCat("Dependee \"", dirInfoFile,
1399 "\" is newer than depender \"",
1400 internalDependFile, "\".\n"));
1402 needRescanDirInfo = true;
1406 // Check the implicit dependencies to see if they are up to date.
1407 // The build.make file may have explicit dependencies for the object
1408 // files but these will not affect the scanning process so they need
1409 // not be considered.
1410 cmDepends::DependencyMap validDependencies;
1411 bool needRescanDependencies = false;
1412 if (!needRescanDirInfo) {
1413 cmDependsC checker;
1414 checker.SetVerbose(verbose);
1415 checker.SetFileTimeCache(ftc);
1416 // cmDependsC::Check() fills the vector validDependencies() with the
1417 // dependencies for those files where they are still valid, i.e.
1418 // neither the files themselves nor any files they depend on have
1419 // changed. We don't do that if the CMakeDirectoryInformation.cmake
1420 // file has changed, because then potentially all dependencies have
1421 // changed. This information is given later on to cmDependsC, which
1422 // then only rescans the files where it did not get valid dependencies
1423 // via this dependency vector. This means that in the normal case, when
1424 // only few or one file have been edited, then also only this one file
1425 // is actually scanned again, instead of all files for this target.
1426 needRescanDependencies =
1427 !checker.Check(dependFile, internalDependFile, validDependencies);
1430 if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
1431 // The dependencies must be regenerated.
1432 if (verbose) {
1433 std::string targetName = cmSystemTools::GetFilenameName(targetDir);
1434 targetName = targetName.substr(0, targetName.length() - 4);
1435 std::string message =
1436 cmStrCat("Scanning dependencies of target ", targetName);
1437 cmSystemTools::MakefileColorEcho(
1438 cmsysTerminal_Color_ForegroundMagenta |
1439 cmsysTerminal_Color_ForegroundBold,
1440 message.c_str(), true, color);
1443 status = this->ScanDependencies(targetDir, dependFile,
1444 internalDependFile, validDependencies);
1448 auto depends =
1449 this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_DEPENDENCY_FILES");
1450 if (!depends.empty()) {
1451 // dependencies are managed by compiler
1452 cmList depFiles{ depends, cmList::EmptyElements::Yes };
1453 std::string const internalDepFile =
1454 targetDir + "/compiler_depend.internal";
1455 std::string const depFile = targetDir + "/compiler_depend.make";
1456 cmDepends::DependencyMap dependencies;
1457 cmDependsCompiler depsManager;
1458 bool projectOnly = cmIsOn(
1459 this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_IN_PROJECT_ONLY"));
1461 depsManager.SetVerbose(verbose);
1462 depsManager.SetLocalGenerator(this);
1464 if (!depsManager.CheckDependencies(
1465 internalDepFile, depFiles, dependencies,
1466 projectOnly ? NotInProjectDir(this->GetSourceDirectory(),
1467 this->GetBinaryDirectory())
1468 : std::function<bool(const std::string&)>())) {
1469 // regenerate dependencies files
1470 if (verbose) {
1471 std::string targetName = cmCMakePath(targetDir)
1472 .GetFileName()
1473 .RemoveExtension()
1474 .GenericString();
1475 auto message =
1476 cmStrCat("Consolidate compiler generated dependencies of target ",
1477 targetName);
1478 cmSystemTools::MakefileColorEcho(
1479 cmsysTerminal_Color_ForegroundMagenta |
1480 cmsysTerminal_Color_ForegroundBold,
1481 message.c_str(), true, color);
1484 // Open the make depends file. This should be copy-if-different
1485 // because the make tool may try to reload it needlessly otherwise.
1486 cmGeneratedFileStream ruleFileStream(
1487 depFile, false, this->GlobalGenerator->GetMakefileEncoding());
1488 ruleFileStream.SetCopyIfDifferent(true);
1489 if (!ruleFileStream) {
1490 return false;
1493 // Open the cmake dependency tracking file. This should not be
1494 // copy-if-different because dependencies are re-scanned when it is
1495 // older than the DependInfo.cmake.
1496 cmGeneratedFileStream internalRuleFileStream(
1497 internalDepFile, false, this->GlobalGenerator->GetMakefileEncoding());
1498 if (!internalRuleFileStream) {
1499 return false;
1502 this->WriteDisclaimer(ruleFileStream);
1503 this->WriteDisclaimer(internalRuleFileStream);
1505 depsManager.WriteDependencies(dependencies, ruleFileStream,
1506 internalRuleFileStream);
1510 // The dependencies are already up-to-date.
1511 return status;
1514 bool cmLocalUnixMakefileGenerator3::ScanDependencies(
1515 std::string const& targetDir, std::string const& dependFile,
1516 std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
1518 // Read the directory information file.
1519 cmMakefile* mf = this->Makefile;
1520 bool haveDirectoryInfo = false;
1522 std::string dirInfoFile =
1523 cmStrCat(this->GetCurrentBinaryDirectory(),
1524 "/CMakeFiles/CMakeDirectoryInformation.cmake");
1525 if (mf->ReadListFile(dirInfoFile) &&
1526 !cmSystemTools::GetErrorOccurredFlag()) {
1527 haveDirectoryInfo = true;
1531 // Lookup useful directory information.
1532 if (haveDirectoryInfo) {
1533 // Test whether we need to force Unix paths.
1534 if (cmValue force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
1535 if (!force.IsOff()) {
1536 cmSystemTools::SetForceUnixPaths(true);
1540 // Setup relative path top directories.
1541 cmValue relativePathTopSource =
1542 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE");
1543 cmValue relativePathTopBinary =
1544 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY");
1545 if (relativePathTopSource && relativePathTopBinary) {
1546 this->SetRelativePathTop(*relativePathTopSource, *relativePathTopBinary);
1548 } else {
1549 cmSystemTools::Error("Directory Information file not found");
1552 // Open the make depends file. This should be copy-if-different
1553 // because the make tool may try to reload it needlessly otherwise.
1554 cmGeneratedFileStream ruleFileStream(
1555 dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
1556 ruleFileStream.SetCopyIfDifferent(true);
1557 if (!ruleFileStream) {
1558 return false;
1561 // Open the cmake dependency tracking file. This should not be
1562 // copy-if-different because dependencies are re-scanned when it is
1563 // older than the DependInfo.cmake.
1564 cmGeneratedFileStream internalRuleFileStream(
1565 internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
1566 if (!internalRuleFileStream) {
1567 return false;
1570 this->WriteDisclaimer(ruleFileStream);
1571 this->WriteDisclaimer(internalRuleFileStream);
1573 // for each language we need to scan, scan it
1574 cmList langs{ mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES") };
1575 for (std::string const& lang : langs) {
1576 // construct the checker
1577 // Create the scanner for this language
1578 std::unique_ptr<cmDepends> scanner;
1579 if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
1580 lang == "OBJC" || lang == "OBJCXX" || lang == "CUDA" ||
1581 lang == "HIP" || lang == "ISPC") {
1582 // TODO: Handle RC (resource files) dependencies correctly.
1583 scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
1585 #ifndef CMAKE_BOOTSTRAP
1586 else if (lang == "Fortran") {
1587 ruleFileStream << "# Note that incremental build could trigger "
1588 << "a call to cmake_copy_f90_mod on each re-build\n";
1589 scanner = cm::make_unique<cmDependsFortran>(this);
1590 } else if (lang == "Java") {
1591 scanner = cm::make_unique<cmDependsJava>();
1593 #endif
1595 if (scanner) {
1596 scanner->SetLocalGenerator(this);
1597 scanner->SetFileTimeCache(
1598 this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
1599 scanner->SetLanguage(lang);
1600 scanner->SetTargetDirectory(targetDir);
1601 scanner->Write(ruleFileStream, internalRuleFileStream);
1605 return true;
1608 void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
1610 cmMakefile* mf = this->Makefile;
1612 // Get the string listing the multiple output pairs.
1613 cmValue pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
1614 if (!pairs_string) {
1615 return;
1618 // Convert the string to a list and preserve empty entries.
1619 cmList pairs{ *pairs_string, cmList::EmptyElements::Yes };
1620 for (auto i = pairs.begin(); i != pairs.end() && (i + 1) != pairs.end();) {
1621 const std::string& depender = *i++;
1622 const std::string& dependee = *i++;
1624 // If the depender is missing then delete the dependee to make
1625 // sure both will be regenerated.
1626 if (cmSystemTools::FileExists(dependee) &&
1627 !cmSystemTools::FileExists(depender)) {
1628 if (verbose) {
1629 cmSystemTools::Stdout(cmStrCat(
1630 "Deleting primary custom command output \"", dependee,
1631 "\" because another output \"", depender, "\" does not exist.\n"));
1633 cmSystemTools::RemoveFile(dependee);
1638 void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
1639 std::ostream& ruleFileStream)
1641 this->WriteDisclaimer(ruleFileStream);
1643 // Write the main entry point target. This must be the VERY first
1644 // target so that make with no arguments will run it.
1646 // Just depend on the all target to drive the build.
1647 std::vector<std::string> depends;
1648 std::vector<std::string> no_commands;
1649 depends.emplace_back("all");
1651 // Write the rule.
1652 this->WriteMakeRule(ruleFileStream,
1653 "Default target executed when no arguments are "
1654 "given to make.",
1655 "default_target", depends, no_commands, true);
1657 // Help out users that try "gmake target1 target2 -j".
1658 cmGlobalUnixMakefileGenerator3* gg =
1659 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
1660 if (gg->AllowNotParallel()) {
1661 std::vector<std::string> no_depends;
1662 this->WriteMakeRule(ruleFileStream,
1663 "Allow only one \"make -f "
1664 "Makefile2\" at a time, but pass "
1665 "parallelism.",
1666 ".NOTPARALLEL", no_depends, no_commands, false);
1670 this->WriteSpecialTargetsTop(ruleFileStream);
1672 // Include the progress variables for the target.
1673 // Write all global targets
1674 this->WriteDivider(ruleFileStream);
1675 ruleFileStream << "# Targets provided globally by CMake.\n"
1676 << "\n";
1677 const auto& targets = this->GetGeneratorTargets();
1678 for (const auto& gt : targets) {
1679 if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
1680 std::string targetString =
1681 "Special rule for the target " + gt->GetName();
1682 std::vector<std::string> commands;
1683 std::vector<std::string> depends;
1685 cmValue p = gt->GetProperty("EchoString");
1686 const char* text = p ? p->c_str() : "Running external command ...";
1687 depends.reserve(gt->GetUtilities().size());
1688 for (BT<std::pair<std::string, bool>> const& u : gt->GetUtilities()) {
1689 depends.push_back(u.Value.first);
1691 this->AppendEcho(commands, text,
1692 cmLocalUnixMakefileGenerator3::EchoGlobal);
1694 // Global targets store their rules in pre- and post-build commands.
1695 this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
1696 this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
1697 this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt.get(),
1698 this->GetCurrentBinaryDirectory());
1699 this->AppendCustomCommands(commands, gt->GetPostBuildCommands(),
1700 gt.get(), this->GetCurrentBinaryDirectory());
1701 std::string targetName = gt->GetName();
1702 this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
1703 depends, commands, true);
1705 // Provide a "/fast" version of the target.
1706 depends.clear();
1707 if ((targetName == "install") || (targetName == "install/local") ||
1708 (targetName == "install/strip")) {
1709 // Provide a fast install target that does not depend on all
1710 // but has the same command.
1711 depends.emplace_back("preinstall/fast");
1712 } else {
1713 // Just forward to the real target so at least it will work.
1714 depends.push_back(targetName);
1715 commands.clear();
1717 targetName += "/fast";
1718 this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
1719 depends, commands, true);
1723 std::vector<std::string> depends;
1724 std::vector<std::string> commands;
1726 // Write the all rule.
1727 std::string recursiveTarget =
1728 cmStrCat(this->GetCurrentBinaryDirectory(), "/all");
1730 bool regenerate =
1731 !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
1732 if (regenerate) {
1733 depends.emplace_back("cmake_check_build_system");
1736 std::string progressDir =
1737 cmStrCat(this->GetBinaryDirectory(), "/CMakeFiles");
1739 std::ostringstream progCmd;
1740 progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
1741 progCmd << this->ConvertToOutputFormat(progressDir,
1742 cmOutputConverter::SHELL);
1744 std::string progressFile = "/CMakeFiles/progress.marks";
1745 std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
1746 progCmd << " "
1747 << this->ConvertToOutputFormat(progressFileNameFull,
1748 cmOutputConverter::SHELL);
1749 commands.push_back(progCmd.str());
1751 std::string mf2Dir = "CMakeFiles/Makefile2";
1752 commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1753 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1754 this->GetCurrentBinaryDirectory());
1756 std::ostringstream progCmd;
1757 progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
1758 progCmd << this->ConvertToOutputFormat(progressDir,
1759 cmOutputConverter::SHELL);
1760 progCmd << " 0";
1761 commands.push_back(progCmd.str());
1763 this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
1764 commands, true);
1766 // Write the clean rule.
1767 recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/clean");
1768 commands.clear();
1769 depends.clear();
1770 commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1771 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1772 this->GetCurrentBinaryDirectory());
1773 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
1774 depends, commands, true);
1775 commands.clear();
1776 depends.clear();
1777 depends.emplace_back("clean");
1778 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
1779 depends, commands, true);
1781 // Write the preinstall rule.
1782 recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/preinstall");
1783 commands.clear();
1784 depends.clear();
1785 cmValue noall =
1786 this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
1787 if (noall.IsOff()) {
1788 // Drive the build before installing.
1789 depends.emplace_back("all");
1790 } else if (regenerate) {
1791 // At least make sure the build system is up to date.
1792 depends.emplace_back("cmake_check_build_system");
1794 commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1795 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1796 this->GetCurrentBinaryDirectory());
1797 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1798 "preinstall", depends, commands, true);
1799 depends.clear();
1800 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1801 "preinstall/fast", depends, commands, true);
1803 if (regenerate) {
1804 // write the depend rule, really a recompute depends rule
1805 depends.clear();
1806 commands.clear();
1807 cmake* cm = this->GlobalGenerator->GetCMakeInstance();
1808 if (cm->DoWriteGlobVerifyTarget()) {
1809 std::string rescanRule =
1810 cmStrCat("$(CMAKE_COMMAND) -P ",
1811 this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
1812 cmOutputConverter::SHELL));
1813 commands.push_back(rescanRule);
1815 std::string cmakefileName = "CMakeFiles/Makefile.cmake";
1817 std::string runRule = cmStrCat(
1818 "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) ",
1819 cm->GetIgnoreWarningAsError() ? "--compile-no-warning-as-error " : "",
1820 "--check-build-system ",
1821 this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
1822 " 1");
1823 commands.push_back(std::move(runRule));
1825 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1826 this->GetCurrentBinaryDirectory());
1827 this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
1828 commands, true);
1832 void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
1833 bool verbose)
1835 // Get the list of target files to check
1836 cmValue infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
1837 if (!infoDef) {
1838 return;
1840 cmList files{ *infoDef };
1842 // Each depend information file corresponds to a target. Clear the
1843 // dependencies for that target.
1844 cmDepends clearer;
1845 clearer.SetVerbose(verbose);
1846 for (std::string const& file : files) {
1847 auto snapshot = mf->GetState()->CreateBaseSnapshot();
1848 cmMakefile lmf(mf->GetGlobalGenerator(), snapshot);
1849 lmf.ReadListFile(file);
1851 if (!lmf.GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES").empty()) {
1852 std::string dir = cmSystemTools::GetFilenamePath(file);
1854 // Clear the implicit dependency makefile.
1855 std::string dependFile = dir + "/depend.make";
1856 clearer.Clear(dependFile);
1858 // Remove the internal dependency check file to force
1859 // regeneration.
1860 std::string internalDependFile = dir + "/depend.internal";
1861 cmSystemTools::RemoveFile(internalDependFile);
1864 auto depsFiles = lmf.GetSafeDefinition("CMAKE_DEPENDS_DEPENDENCY_FILES");
1865 if (!depsFiles.empty()) {
1866 auto dir = cmCMakePath(file).GetParentPath();
1867 // Clear the implicit dependency makefile.
1868 auto depFile = cmCMakePath(dir).Append("compiler_depend.make");
1869 clearer.Clear(depFile.GenericString());
1871 // Remove the internal dependency check file
1872 auto internalDepFile =
1873 cmCMakePath(dir).Append("compiler_depend.internal");
1874 cmSystemTools::RemoveFile(internalDepFile.GenericString());
1876 // Touch timestamp file to force dependencies regeneration
1877 auto DepTimestamp = cmCMakePath(dir).Append("compiler_depend.ts");
1878 cmSystemTools::Touch(DepTimestamp.GenericString(), true);
1880 // clear the dependencies files generated by the compiler
1881 cmList dependencies{ depsFiles, cmList::EmptyElements::Yes };
1882 cmDependsCompiler depsManager;
1883 depsManager.SetVerbose(verbose);
1884 depsManager.ClearDependencies(dependencies);
1889 void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
1890 std::ostream& cmakefileStream, cmGeneratorTarget* target)
1892 // To enable dependencies filtering
1893 cmakefileStream << "\n"
1894 << "# Consider dependencies only in project.\n"
1895 << "set(CMAKE_DEPENDS_IN_PROJECT_ONLY "
1896 << (cmIsOn(this->Makefile->GetSafeDefinition(
1897 "CMAKE_DEPENDS_IN_PROJECT_ONLY"))
1898 ? "ON"
1899 : "OFF")
1900 << ")\n\n";
1902 bool requireFortran = false;
1903 if (target->HaveFortranSources(this->GetConfigName())) {
1904 requireFortran = true;
1907 auto const& implicitLangs =
1908 this->GetImplicitDepends(target, cmDependencyScannerKind::CMake);
1910 // list the languages
1911 cmakefileStream << "# The set of languages for which implicit "
1912 "dependencies are needed:\n";
1913 cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
1914 for (auto const& implicitLang : implicitLangs) {
1915 cmakefileStream << " \"" << implicitLang.first << "\"\n";
1916 if (requireFortran && implicitLang.first == "Fortran"_s) {
1917 requireFortran = false;
1920 if (requireFortran) {
1921 cmakefileStream << " \"Fortran\"\n";
1923 cmakefileStream << " )\n";
1925 if (!implicitLangs.empty()) {
1926 // now list the files for each language
1927 cmakefileStream
1928 << "# The set of files for implicit dependencies of each language:\n";
1929 for (auto const& implicitLang : implicitLangs) {
1930 const auto& lang = implicitLang.first;
1932 cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << lang << "\n";
1933 auto const& implicitPairs = implicitLang.second;
1935 // for each file pair
1936 for (auto const& implicitPair : implicitPairs) {
1937 for (auto const& di : implicitPair.second) {
1938 cmakefileStream << " \"" << di << "\" ";
1939 cmakefileStream << "\"" << implicitPair.first << "\"\n";
1942 cmakefileStream << " )\n";
1944 // Tell the dependency scanner what compiler is used.
1945 std::string cidVar = cmStrCat("CMAKE_", lang, "_COMPILER_ID");
1946 cmValue cid = this->Makefile->GetDefinition(cidVar);
1947 if (cmNonempty(cid)) {
1948 cmakefileStream << "set(CMAKE_" << lang << "_COMPILER_ID \"" << *cid
1949 << "\")\n";
1952 if (lang == "Fortran") {
1953 std::string smodSep =
1954 this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
1955 std::string smodExt =
1956 this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
1957 cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_SEP \"" << smodSep
1958 << "\")\n";
1959 cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_EXT \"" << smodExt
1960 << "\")\n";
1963 // Build a list of preprocessor definitions for the target.
1964 std::set<std::string> defines;
1965 this->GetTargetDefines(target, this->GetConfigName(), lang, defines);
1966 if (!defines.empty()) {
1967 /* clang-format off */
1968 cmakefileStream
1969 << "\n"
1970 << "# Preprocessor definitions for this target.\n"
1971 << "set(CMAKE_TARGET_DEFINITIONS_" << lang << "\n";
1972 /* clang-format on */
1973 for (std::string const& define : defines) {
1974 cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define)
1975 << "\n";
1977 cmakefileStream << " )\n";
1980 // Target-specific include directories:
1981 cmakefileStream << "\n"
1982 << "# The include file search paths:\n";
1983 cmakefileStream << "set(CMAKE_" << lang << "_TARGET_INCLUDE_PATH\n";
1984 std::vector<std::string> includes;
1986 this->GetIncludeDirectories(includes, target, lang,
1987 this->GetConfigName());
1988 std::string const& binaryDir = this->GetState()->GetBinaryDirectory();
1989 if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
1990 std::string const& sourceDir = this->GetState()->GetSourceDirectory();
1991 cm::erase_if(includes, ::NotInProjectDir(sourceDir, binaryDir));
1993 for (std::string const& include : includes) {
1994 cmakefileStream << " \"" << this->MaybeRelativeToTopBinDir(include)
1995 << "\"\n";
1997 cmakefileStream << " )\n";
2000 // Store include transform rule properties. Write the directory
2001 // rules first because they may be overridden by later target rules.
2002 cmList transformRules;
2003 if (cmValue xform =
2004 this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
2005 transformRules.assign(*xform);
2007 if (cmValue xform =
2008 target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
2009 transformRules.append(*xform);
2011 if (!transformRules.empty()) {
2012 cmakefileStream << "\nset(CMAKE_INCLUDE_TRANSFORMS\n";
2013 for (std::string const& tr : transformRules) {
2014 cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr)
2015 << "\n";
2017 cmakefileStream << " )\n";
2021 auto const& compilerLangs =
2022 this->GetImplicitDepends(target, cmDependencyScannerKind::Compiler);
2024 // list the dependency files managed by the compiler
2025 cmakefileStream << "\n# The set of dependency files which are needed:\n";
2026 cmakefileStream << "set(CMAKE_DEPENDS_DEPENDENCY_FILES\n";
2027 for (auto const& compilerLang : compilerLangs) {
2028 auto const& compilerPairs = compilerLang.second;
2029 if (compilerLang.first == "CUSTOM"_s) {
2030 for (auto const& compilerPair : compilerPairs) {
2031 for (auto const& src : compilerPair.second) {
2032 cmakefileStream << R"( "" ")"
2033 << this->MaybeRelativeToTopBinDir(compilerPair.first)
2034 << R"(" "custom" ")"
2035 << this->MaybeRelativeToTopBinDir(src) << "\"\n";
2038 } else if (compilerLang.first == "LINK"_s) {
2039 auto depFormat = this->Makefile->GetDefinition(
2040 cmStrCat("CMAKE_", target->GetLinkerLanguage(this->GetConfigName()),
2041 "_LINKER_DEPFILE_FORMAT"));
2042 for (auto const& compilerPair : compilerPairs) {
2043 for (auto const& src : compilerPair.second) {
2044 cmakefileStream << R"( "" ")"
2045 << this->MaybeRelativeToTopBinDir(compilerPair.first)
2046 << "\" \"" << depFormat << "\" \""
2047 << this->MaybeRelativeToTopBinDir(src) << "\"\n";
2050 } else {
2051 auto depFormat = this->Makefile->GetSafeDefinition(
2052 cmStrCat("CMAKE_", compilerLang.first, "_DEPFILE_FORMAT"));
2053 for (auto const& compilerPair : compilerPairs) {
2054 for (auto const& src : compilerPair.second) {
2055 cmakefileStream << " \"" << src << "\" \""
2056 << this->MaybeRelativeToTopBinDir(compilerPair.first)
2057 << "\" \"" << depFormat << "\" \""
2058 << this->MaybeRelativeToTopBinDir(compilerPair.first)
2059 << ".d\"\n";
2064 cmakefileStream << " )\n";
2067 void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
2069 os << "# CMAKE generated file: DO NOT EDIT!\n"
2070 << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
2071 << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
2072 << cmVersion::GetMinorVersion() << "\n\n";
2075 std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
2076 const std::string& makefile, const std::string& tgt)
2078 // Call make on the given file.
2079 std::string cmd = cmStrCat(
2080 "$(MAKE) $(MAKESILENT) -f ",
2081 this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL), ' ');
2083 cmGlobalUnixMakefileGenerator3* gg =
2084 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
2085 // Pass down verbosity level.
2086 if (!gg->MakeSilentFlag.empty()) {
2087 cmd += gg->MakeSilentFlag;
2088 cmd += " ";
2091 // Most unix makes will pass the command line flags to make down to
2092 // sub-invoked makes via an environment variable. However, some
2093 // makes do not support that, so you have to pass the flags
2094 // explicitly.
2095 if (gg->PassMakeflags) {
2096 cmd += "-$(MAKEFLAGS) ";
2099 // Add the target.
2100 if (!tgt.empty()) {
2101 // The make target is always relative to the top of the build tree.
2102 std::string tgt2 = this->MaybeRelativeToTopBinDir(tgt);
2104 // The target may have been written with windows paths.
2105 cmSystemTools::ConvertToOutputSlashes(tgt2);
2107 // Escape one extra time if the make tool requires it.
2108 if (this->MakeCommandEscapeTargetTwice) {
2109 tgt2 = this->EscapeForShell(tgt2, true, false);
2112 // The target name is now a string that should be passed verbatim
2113 // on the command line.
2114 cmd += this->EscapeForShell(tgt2, true, false);
2116 return cmd;
2119 void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
2121 os << "#======================================"
2122 "=======================================\n";
2125 void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
2126 const std::string& s)
2128 // Write the given string to the stream with escaping to get it back
2129 // into CMake through the lexical scanner.
2130 os << '"';
2131 for (char c : s) {
2132 if (c == '\\') {
2133 os << "\\\\";
2134 } else if (c == '"') {
2135 os << "\\\"";
2136 } else {
2137 os << c;
2140 os << '"';
2143 std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
2144 const std::string& p, bool useWatcomQuote)
2146 // Split the path into its components.
2147 std::vector<std::string> components;
2148 cmSystemTools::SplitPath(p, components);
2150 // Open the quoted result.
2151 std::string result;
2152 if (useWatcomQuote) {
2153 #if defined(_WIN32) && !defined(__CYGWIN__)
2154 result = "'";
2155 #else
2156 result = "\"'";
2157 #endif
2158 } else {
2159 result = "\"";
2162 // Return an empty path if there are no components.
2163 if (!components.empty()) {
2164 // Choose a slash direction and fix root component.
2165 const char* slash = "/";
2166 #if defined(_WIN32) && !defined(__CYGWIN__)
2167 if (!cmSystemTools::GetForceUnixPaths()) {
2168 slash = "\\";
2169 for (char& i : components[0]) {
2170 if (i == '/') {
2171 i = '\\';
2175 #endif
2177 // Begin the quoted result with the root component.
2178 result += components[0];
2180 if (components.size() > 1) {
2181 // Now add the rest of the components separated by the proper slash
2182 // direction for this platform.
2183 auto compEnd = std::remove(components.begin() + 1, components.end() - 1,
2184 std::string());
2185 auto compStart = components.begin() + 1;
2186 result += cmJoin(cmMakeRange(compStart, compEnd), slash);
2187 // Only the last component can be empty to avoid double slashes.
2188 result += slash;
2189 result += components.back();
2193 // Close the quoted result.
2194 if (useWatcomQuote) {
2195 #if defined(_WIN32) && !defined(__CYGWIN__)
2196 result += "'";
2197 #else
2198 result += "'\"";
2199 #endif
2200 } else {
2201 result += "\"";
2204 return result;
2207 std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
2208 cmGeneratorTarget const* target) const
2210 std::string dir = cmStrCat("CMakeFiles/", target->GetName());
2211 #if defined(__VMS)
2212 dir += "_dir";
2213 #else
2214 dir += ".dir";
2215 #endif
2216 return dir;
2219 cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
2220 cmLocalUnixMakefileGenerator3::GetImplicitDepends(
2221 const cmGeneratorTarget* tgt, cmDependencyScannerKind scanner)
2223 return this->ImplicitDepends[tgt->GetName()][scanner];
2226 void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
2227 const cmGeneratorTarget* tgt, const std::string& lang,
2228 const std::string& obj, const std::string& src,
2229 cmDependencyScannerKind scanner)
2231 this->ImplicitDepends[tgt->GetName()][scanner][lang][obj].push_back(src);
2234 void cmLocalUnixMakefileGenerator3::CreateCDCommand(
2235 std::vector<std::string>& commands, std::string const& tgtDir,
2236 std::string const& relDir)
2238 // do we need to cd?
2239 if (tgtDir == relDir) {
2240 return;
2243 // In a Windows shell we must change drive letter too. The shell
2244 // used by NMake and Borland make does not support "cd /d" so this
2245 // feature simply cannot work with them (Borland make does not even
2246 // support changing the drive letter with just "d:").
2247 const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
2249 cmGlobalUnixMakefileGenerator3* gg =
2250 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
2251 if (!gg->UnixCD) {
2252 // On Windows we must perform each step separately and then change
2253 // back because the shell keeps the working directory between
2254 // commands.
2255 std::string cmd =
2256 cmStrCat(cd_cmd, this->ConvertToOutputForExisting(tgtDir));
2257 commands.insert(commands.begin(), cmd);
2259 // Change back to the starting directory.
2260 cmd = cmStrCat(cd_cmd, this->ConvertToOutputForExisting(relDir));
2261 commands.push_back(std::move(cmd));
2262 } else {
2263 // On UNIX we must construct a single shell command to change
2264 // directory and build because make resets the directory between
2265 // each command.
2266 std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
2267 std::string prefix = cd_cmd + outputForExisting + " && ";
2268 std::transform(commands.begin(), commands.end(), commands.begin(),
2269 [&prefix](std::string const& s) { return prefix + s; });