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"
13 #include <cm/string_view>
15 #include <cmext/algorithm>
16 #include <cmext/string_view>
18 #include "cmsys/FStream.hxx"
19 #include "cmsys/Terminal.h"
21 #include "cmCMakePath.h"
22 #include "cmCustomCommand.h" // IWYU pragma: keep
23 #include "cmCustomCommandGenerator.h"
24 #include "cmDependsCompiler.h"
25 #include "cmFileTimeCache.h"
26 #include "cmGeneratedFileStream.h"
27 #include "cmGeneratorExpression.h"
28 #include "cmGeneratorTarget.h"
29 #include "cmGlobalGenerator.h"
30 #include "cmGlobalUnixMakefileGenerator3.h"
31 #include "cmListFileCache.h"
32 #include "cmLocalGenerator.h"
33 #include "cmMakefile.h"
34 #include "cmMakefileTargetGenerator.h"
35 #include "cmOutputConverter.h"
37 #include "cmRulePlaceholderExpander.h"
38 #include "cmSourceFile.h"
40 #include "cmStateSnapshot.h"
41 #include "cmStateTypes.h"
42 #include "cmStringAlgorithms.h"
43 #include "cmSystemTools.h"
44 #include "cmTargetDepend.h"
46 #include "cmVersion.h"
49 // Include dependency scanners for supported languages. Only the
50 // C/C++ scanner is needed for bootstrapping CMake.
51 #include "cmDependsC.h"
52 #ifndef CMAKE_BOOTSTRAP
53 # include "cmDependsFortran.h"
54 # include "cmDependsJava.h"
58 // Helper function used below.
59 std::string cmSplitExtension(std::string const& in, std::string& base)
62 std::string::size_type dot_pos = in.rfind('.');
63 if (dot_pos != std::string::npos) {
64 // Remove the extension first in case &base == &in.
65 ext = in.substr(dot_pos);
66 base = in.substr(0, dot_pos);
73 // Helper predicate for removing absolute paths that don't point to the
74 // source or binary directory. It is used when CMAKE_DEPENDS_IN_PROJECT_ONLY
75 // is set ON, to only consider in-project dependencies during the build.
79 // Constructor with the source and binary directory's path
80 NotInProjectDir(cm::string_view sourceDir, cm::string_view binaryDir)
81 : SourceDir(sourceDir)
82 , BinaryDir(binaryDir)
86 // Operator evaluating the predicate
87 bool operator()(const std::string& p) const
89 auto path = cmCMakePath(p).Normal();
91 // Keep all relative paths:
92 if (path.IsRelative()) {
96 // If it's an absolute path, check if it starts with the source
98 return !(cmCMakePath(this->SourceDir).IsPrefix(path) ||
99 cmCMakePath(this->BinaryDir).IsPrefix(path));
103 // The path to the source directory
104 cm::string_view SourceDir;
105 // The path to the binary directory
106 cm::string_view BinaryDir;
110 cmLocalUnixMakefileGenerator3::cmLocalUnixMakefileGenerator3(
111 cmGlobalGenerator* gg, cmMakefile* mf)
112 : cmLocalCommonGenerator(gg, mf, WorkDir::CurBin)
114 this->MakefileVariableSize = 0;
115 this->ColorMakefile = false;
116 this->SkipPreprocessedSourceRules = false;
117 this->SkipAssemblySourceRules = false;
118 this->MakeCommandEscapeTargetTwice = false;
119 this->BorlandMakeCurlyHack = false;
122 cmLocalUnixMakefileGenerator3::~cmLocalUnixMakefileGenerator3() = default;
124 std::string cmLocalUnixMakefileGenerator3::GetConfigName() const
126 auto const& configNames = this->GetConfigNames();
127 assert(configNames.size() == 1);
128 return configNames.front();
131 void cmLocalUnixMakefileGenerator3::Generate()
133 // Record whether some options are enabled to avoid checking many
135 if (!this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
136 if (this->Makefile->IsSet("CMAKE_COLOR_MAKEFILE")) {
137 this->ColorMakefile = this->Makefile->IsOn("CMAKE_COLOR_MAKEFILE");
139 this->ColorMakefile = this->Makefile->IsOn("CMAKE_COLOR_DIAGNOSTICS");
142 this->SkipPreprocessedSourceRules =
143 this->Makefile->IsOn("CMAKE_SKIP_PREPROCESSED_SOURCE_RULES");
144 this->SkipAssemblySourceRules =
145 this->Makefile->IsOn("CMAKE_SKIP_ASSEMBLY_SOURCE_RULES");
147 // Generate the rule files for each target.
148 cmGlobalUnixMakefileGenerator3* gg =
149 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
150 for (cmGeneratorTarget* gt :
151 this->GlobalGenerator->GetLocalGeneratorTargetsInOrder(this)) {
152 if (!gt->IsInBuildSystem()) {
156 auto& gtVisited = this->GetCommandsVisited(gt);
157 const auto& deps = this->GlobalGenerator->GetTargetDirectDepends(gt);
158 for (const auto& d : deps) {
159 // Take the union of visited source files of custom commands
160 auto depVisited = this->GetCommandsVisited(d);
161 gtVisited.insert(depVisited.begin(), depVisited.end());
164 std::unique_ptr<cmMakefileTargetGenerator> tg(
165 cmMakefileTargetGenerator::New(gt));
167 tg->WriteRuleFiles();
168 gg->RecordTargetProgress(tg.get());
172 // write the local Makefile
173 this->WriteLocalMakefile();
175 // Write the cmake file with information for this directory.
176 this->WriteDirectoryInformationFile();
179 void cmLocalUnixMakefileGenerator3::ComputeHomeRelativeOutputPath()
181 // Compute the path to use when referencing the current output
182 // directory from the top output directory.
183 this->HomeRelativeOutputPath =
184 this->MaybeRelativeToTopBinDir(this->GetCurrentBinaryDirectory());
185 if (this->HomeRelativeOutputPath == ".") {
186 this->HomeRelativeOutputPath.clear();
188 if (!this->HomeRelativeOutputPath.empty()) {
189 this->HomeRelativeOutputPath += "/";
193 void cmLocalUnixMakefileGenerator3::GetLocalObjectFiles(
194 std::map<std::string, LocalObjectInfo>& localObjectFiles)
196 for (const auto& gt : this->GetGeneratorTargets()) {
197 if (!gt->CanCompileSources()) {
200 std::vector<cmSourceFile const*> objectSources;
201 gt->GetObjectSources(objectSources, this->GetConfigName());
202 // Compute full path to object file directory for this target.
203 std::string dir = cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(),
204 '/', this->GetTargetDirectory(gt.get()), '/');
205 // Compute the name of each object file.
206 for (cmSourceFile const* sf : objectSources) {
207 bool hasSourceExtension = true;
208 std::string objectName =
209 this->GetObjectFileNameWithoutTarget(*sf, dir, &hasSourceExtension);
210 if (cmSystemTools::FileIsFullPath(objectName)) {
211 objectName = cmSystemTools::GetFilenameName(objectName);
213 LocalObjectInfo& info = localObjectFiles[objectName];
214 info.HasSourceExtension = hasSourceExtension;
215 info.emplace_back(gt.get(), sf->GetLanguage());
220 void cmLocalUnixMakefileGenerator3::GetIndividualFileTargets(
221 std::vector<std::string>& targets)
223 std::map<std::string, LocalObjectInfo> localObjectFiles;
224 this->GetLocalObjectFiles(localObjectFiles);
225 for (auto const& localObjectFile : localObjectFiles) {
226 targets.push_back(localObjectFile.first);
228 std::string::size_type dot_pos = localObjectFile.first.rfind(".");
229 std::string base = localObjectFile.first.substr(0, dot_pos);
230 if (localObjectFile.second.HasPreprocessRule) {
231 targets.push_back(base + ".i");
234 if (localObjectFile.second.HasAssembleRule) {
235 targets.push_back(base + ".s");
240 void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
242 // generate the includes
243 std::string ruleFileName = "Makefile";
245 // Open the rule file. This should be copy-if-different because the
246 // rules may depend on this file itself.
247 std::string ruleFileNameFull = this->ConvertToFullPath(ruleFileName);
248 cmGeneratedFileStream ruleFileStream(
249 ruleFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
250 if (!ruleFileStream) {
253 // always write the top makefile
254 if (!this->IsRootMakefile()) {
255 ruleFileStream.SetCopyIfDifferent(true);
258 // write the all rules
259 this->WriteLocalAllRules(ruleFileStream);
261 // only write local targets unless at the top Keep track of targets already
263 std::set<std::string> emittedTargets;
264 if (!this->IsRootMakefile()) {
265 // write our targets, and while doing it collect up the object
267 this->WriteLocalMakefileTargets(ruleFileStream, emittedTargets);
269 cmGlobalUnixMakefileGenerator3* gg =
270 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
271 gg->WriteConvenienceRules(ruleFileStream, emittedTargets);
274 bool do_preprocess_rules = this->GetCreatePreprocessedSourceRules();
275 bool do_assembly_rules = this->GetCreateAssemblySourceRules();
277 std::map<std::string, LocalObjectInfo> localObjectFiles;
278 this->GetLocalObjectFiles(localObjectFiles);
280 // now write out the object rules
281 // for each object file name
282 for (auto& localObjectFile : localObjectFiles) {
283 // Add a convenience rule for building the object file.
284 this->WriteObjectConvenienceRule(
285 ruleFileStream, "target to build an object file", localObjectFile.first,
286 localObjectFile.second);
288 // Check whether preprocessing and assembly rules make sense.
289 // They make sense only for C and C++ sources.
290 bool lang_has_preprocessor = false;
291 bool lang_has_assembly = false;
293 for (LocalObjectEntry const& entry : localObjectFile.second) {
294 if (entry.Language == "C" || entry.Language == "CXX" ||
295 entry.Language == "CUDA" || entry.Language == "Fortran" ||
296 entry.Language == "HIP" || entry.Language == "ISPC") {
297 // Right now, C, C++, CUDA, Fortran, HIP and ISPC have both a
298 // preprocessor and the ability to generate assembly code
299 lang_has_preprocessor = true;
300 lang_has_assembly = true;
305 // Add convenience rules for preprocessed and assembly files.
306 if (lang_has_preprocessor && do_preprocess_rules) {
307 std::string::size_type dot_pos = localObjectFile.first.rfind(".");
308 std::string base = localObjectFile.first.substr(0, dot_pos);
309 this->WriteObjectConvenienceRule(ruleFileStream,
310 "target to preprocess a source file",
311 (base + ".i"), localObjectFile.second);
312 localObjectFile.second.HasPreprocessRule = true;
315 if (lang_has_assembly && do_assembly_rules) {
316 std::string::size_type dot_pos = localObjectFile.first.rfind(".");
317 std::string base = localObjectFile.first.substr(0, dot_pos);
318 this->WriteObjectConvenienceRule(
319 ruleFileStream, "target to generate assembly for a file",
320 (base + ".s"), localObjectFile.second);
321 localObjectFile.second.HasAssembleRule = true;
325 // add a help target as long as there isn;t a real target named help
326 if (emittedTargets.insert("help").second) {
327 cmGlobalUnixMakefileGenerator3* gg =
328 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
329 gg->WriteHelpRule(ruleFileStream, this);
332 this->WriteSpecialTargetsBottom(ruleFileStream);
335 void cmLocalUnixMakefileGenerator3::WriteObjectConvenienceRule(
336 std::ostream& ruleFileStream, const char* comment, const std::string& output,
337 LocalObjectInfo const& info)
339 // If the rule includes the source file extension then create a
340 // version that has the extension removed. The help should include
341 // only the version without source extension.
343 if (info.HasSourceExtension) {
344 // Remove the last extension. This should be kept.
345 std::string outBase1 = output;
346 std::string outExt1 = cmSplitExtension(outBase1, outBase1);
348 // Now remove the source extension and put back the last
350 std::string outNoExt;
351 cmSplitExtension(outBase1, outNoExt);
354 // Add a rule to drive the rule below.
355 std::vector<std::string> depends;
356 depends.emplace_back(output);
357 std::vector<std::string> no_commands;
358 this->WriteMakeRule(ruleFileStream, nullptr, outNoExt, depends,
359 no_commands, true, true);
363 // Recursively make the rule for each target using the object file.
364 std::vector<std::string> commands;
365 for (LocalObjectEntry const& t : info) {
366 std::string tgtMakefileName = this->GetRelativeTargetDirectory(t.Target);
367 std::string targetName = tgtMakefileName;
368 tgtMakefileName += "/build.make";
370 targetName += output;
372 this->GetRecursiveMakeCall(tgtMakefileName, targetName));
374 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
375 this->GetCurrentBinaryDirectory());
377 // Write the rule to the makefile.
378 std::vector<std::string> no_depends;
379 this->WriteMakeRule(ruleFileStream, comment, output, no_depends, commands,
383 void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
384 std::ostream& ruleFileStream, std::set<std::string>& emitted)
386 std::vector<std::string> depends;
387 std::vector<std::string> commands;
389 // for each target we just provide a rule to cd up to the top and do a make
391 std::string localName;
392 for (const auto& target : this->GetGeneratorTargets()) {
393 if ((target->GetType() == cmStateEnums::EXECUTABLE) ||
394 (target->GetType() == cmStateEnums::STATIC_LIBRARY) ||
395 (target->GetType() == cmStateEnums::SHARED_LIBRARY) ||
396 (target->GetType() == cmStateEnums::MODULE_LIBRARY) ||
397 (target->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
398 (target->GetType() == cmStateEnums::UTILITY)) {
399 emitted.insert(target->GetName());
401 // for subdirs add a rule to build this specific target by name.
403 cmStrCat(this->GetRelativeTargetDirectory(target.get()), "/rule");
407 // Build the target for this pass.
408 std::string makefile2 = "CMakeFiles/Makefile2";
409 commands.push_back(this->GetRecursiveMakeCall(makefile2, localName));
410 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
411 this->GetCurrentBinaryDirectory());
412 this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
413 localName, depends, commands, true);
415 // Add a target with the canonical name (no prefix, suffix or path).
416 if (localName != target->GetName()) {
418 depends.push_back(localName);
419 this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
420 target->GetName(), depends, commands, true);
423 // Add a fast rule to build the target
424 std::string makefileName = cmStrCat(
425 this->GetRelativeTargetDirectory(target.get()), "/build.make");
426 // make sure the makefile name is suitable for a makefile
427 std::string makeTargetName =
428 cmStrCat(this->GetRelativeTargetDirectory(target.get()), "/build");
429 localName = cmStrCat(target->GetName(), "/fast");
433 this->GetRecursiveMakeCall(makefileName, makeTargetName));
434 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
435 this->GetCurrentBinaryDirectory());
436 this->WriteMakeRule(ruleFileStream, "fast build rule for target.",
437 localName, depends, commands, true);
439 // Add a local name for the rule to relink the target before
441 if (target->NeedRelinkBeforeInstall(this->GetConfigName())) {
442 makeTargetName = cmStrCat(
443 this->GetRelativeTargetDirectory(target.get()), "/preinstall");
444 localName = cmStrCat(target->GetName(), "/preinstall");
448 this->GetRecursiveMakeCall(makefile2, makeTargetName));
449 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
450 this->GetCurrentBinaryDirectory());
451 this->WriteMakeRule(ruleFileStream,
452 "Manual pre-install relink rule for target.",
453 localName, depends, commands, true);
459 void cmLocalUnixMakefileGenerator3::WriteDirectoryInformationFile()
461 std::string infoFileName =
462 cmStrCat(this->GetCurrentBinaryDirectory(),
463 "/CMakeFiles/CMakeDirectoryInformation.cmake");
465 // Open the output file.
466 cmGeneratedFileStream infoFileStream(infoFileName);
467 if (!infoFileStream) {
471 infoFileStream.SetCopyIfDifferent(true);
472 // Write the do not edit header.
473 this->WriteDisclaimer(infoFileStream);
475 // Setup relative path conversion tops.
476 /* clang-format off */
478 << "# Relative path conversion top directories.\n"
479 << "set(CMAKE_RELATIVE_PATH_TOP_SOURCE \""
480 << this->GetRelativePathTopSource() << "\")\n"
481 << "set(CMAKE_RELATIVE_PATH_TOP_BINARY \""
482 << this->GetRelativePathTopBinary() << "\")\n"
484 /* clang-format on */
486 // Tell the dependency scanner to use unix paths if necessary.
487 if (cmSystemTools::GetForceUnixPaths()) {
488 /* clang-format off */
490 << "# Force unix paths in dependencies.\n"
491 << "set(CMAKE_FORCE_UNIX_PATHS 1)\n"
493 /* clang-format on */
496 // Store the include regular expressions for this directory.
497 infoFileStream << "\n"
498 << "# The C and CXX include file regular expressions for "
499 << "this directory.\n";
500 infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_SCAN ";
501 cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
502 infoFileStream, this->Makefile->GetIncludeRegularExpression());
503 infoFileStream << ")\n";
504 infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_COMPLAIN ";
505 cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
506 infoFileStream, this->Makefile->GetComplainRegularExpression());
507 infoFileStream << ")\n";
509 << "set(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})\n";
510 infoFileStream << "set(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN "
511 "${CMAKE_C_INCLUDE_REGEX_COMPLAIN})\n";
514 std::string cmLocalUnixMakefileGenerator3::ConvertToFullPath(
515 const std::string& localPath)
518 cmStrCat(this->GetCurrentBinaryDirectory(), '/', localPath);
522 const std::string& cmLocalUnixMakefileGenerator3::GetHomeRelativeOutputPath()
524 return this->HomeRelativeOutputPath;
527 std::string cmLocalUnixMakefileGenerator3::ConvertToMakefilePath(
528 std::string const& path) const
530 cmGlobalUnixMakefileGenerator3* gg =
531 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
532 return gg->ConvertToMakefilePath(path);
535 void cmLocalUnixMakefileGenerator3::WriteMakeRule(
536 std::ostream& os, const char* comment, const std::string& target,
537 const std::vector<std::string>& depends,
538 const std::vector<std::string>& commands, bool symbolic, bool in_help)
540 // Make sure there is a target.
541 if (target.empty()) {
542 std::string err("No target for WriteMakeRule! called with comment: ");
546 cmSystemTools::Error(err);
552 // Write the comment describing the rule in the makefile.
555 std::string::size_type lpos = 0;
556 std::string::size_type rpos;
557 while ((rpos = replace.find('\n', lpos)) != std::string::npos) {
558 os << "# " << replace.substr(lpos, rpos - lpos) << "\n";
561 os << "# " << replace.substr(lpos) << "\n";
564 // Construct the left hand side of the rule.
566 this->ConvertToMakefilePath(this->MaybeRelativeToTopBinDir(target));
568 const char* space = "";
569 if (tgt.size() == 1) {
570 // Add a space before the ":" to avoid drive letter confusion on
575 // Mark the rule as symbolic if requested.
578 this->Makefile->GetDefinition("CMAKE_MAKE_SYMBOLIC_RULE")) {
579 os << tgt << space << ": " << *sym << "\n";
584 if (depends.empty()) {
585 // No dependencies. The commands will always run.
586 os << tgt << space << ":\n";
588 // Split dependencies into multiple rule lines. This allows for
589 // very long dependency lists even on older make implementations.
590 for (std::string const& depend : depends) {
591 os << tgt << space << ": "
592 << this->ConvertToMakefilePath(this->MaybeRelativeToTopBinDir(depend))
597 if (!commands.empty()) {
598 // Write the list of commands.
599 os << cmWrap("\t", commands, "", "\n") << "\n";
601 if (symbolic && !this->IsWatcomWMake()) {
602 os << ".PHONY : " << tgt << "\n";
605 // Add the output to the local help if requested.
607 this->LocalHelp.push_back(target);
611 std::string cmLocalUnixMakefileGenerator3::MaybeConvertWatcomShellCommand(
612 std::string const& cmd)
614 if (this->IsWatcomWMake() && cmSystemTools::FileIsFullPath(cmd) &&
615 cmd.find_first_of("( )") != std::string::npos) {
616 // On Watcom WMake use the windows short path for the command
617 // name. This is needed to avoid funny quoting problems on
618 // lines with shell redirection operators.
620 if (cmSystemTools::GetShortPath(cmd, scmd)) {
621 return this->ConvertToOutputFormat(scmd, cmOutputConverter::SHELL);
624 return std::string();
627 void cmLocalUnixMakefileGenerator3::WriteMakeVariables(
628 std::ostream& makefileStream)
630 this->WriteDivider(makefileStream);
631 makefileStream << "# Set environment variables for the build.\n"
633 cmGlobalUnixMakefileGenerator3* gg =
634 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
635 if (gg->DefineWindowsNULL) {
636 makefileStream << "!IF \"$(OS)\" == \"Windows_NT\"\n"
642 if (this->IsWindowsShell()) {
643 makefileStream << "SHELL = cmd.exe\n"
647 /* clang-format off */
649 << "# The shell in which to execute make rules.\n"
650 << "SHELL = /bin/sh\n"
652 /* clang-format on */
656 std::string cmakeShellCommand =
657 this->MaybeConvertWatcomShellCommand(cmSystemTools::GetCMakeCommand());
658 if (cmakeShellCommand.empty()) {
659 cmakeShellCommand = this->ConvertToOutputFormat(
660 cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
663 /* clang-format off */
665 << "# The CMake executable.\n"
666 << "CMAKE_COMMAND = "
671 << "# The command to remove a file.\n"
677 << "# Escaping for special characters.\n"
681 << "# The top-level source directory on which CMake was run.\n"
682 << "CMAKE_SOURCE_DIR = "
683 << this->ConvertToOutputFormat(
684 this->GetSourceDirectory(), cmOutputConverter::SHELL)
688 << "# The top-level build directory on which CMake was run.\n"
689 << "CMAKE_BINARY_DIR = "
690 << this->ConvertToOutputFormat(
691 this->GetBinaryDirectory(), cmOutputConverter::SHELL)
694 /* clang-format on */
697 void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsTop(
698 std::ostream& makefileStream)
700 this->WriteDivider(makefileStream);
701 makefileStream << "# Special targets provided by cmake.\n"
704 std::vector<std::string> no_commands;
705 std::vector<std::string> no_depends;
707 // Special target to cleanup operation of make tool.
708 // This should be the first target except for the default_target in
709 // the interface Makefile.
710 this->WriteMakeRule(makefileStream,
711 "Disable implicit rules so canonical targets will work.",
712 ".SUFFIXES", no_depends, no_commands, false);
714 if (!this->IsNMake() && !this->IsWatcomWMake() &&
715 !this->BorlandMakeCurlyHack) {
716 // turn off RCS and SCCS automatic stuff from gmake
717 constexpr const char* vcs_rules[] = {
718 "%,v", "RCS/%", "RCS/%,v", "SCCS/s.%", "s.%",
720 for (const auto* vcs_rule : vcs_rules) {
721 std::vector<std::string> vcs_depend;
722 vcs_depend.emplace_back(vcs_rule);
723 this->WriteMakeRule(makefileStream, "Disable VCS-based implicit rules.",
724 "%", vcs_depend, no_commands, false);
727 // Add a fake suffix to keep HP happy. Must be max 32 chars for SGI make.
728 std::vector<std::string> depends;
729 depends.emplace_back(".hpux_make_needs_suffix_list");
730 this->WriteMakeRule(makefileStream, nullptr, ".SUFFIXES", depends,
732 if (this->IsWatcomWMake()) {
733 // Switch on WMake feature, if an error or interrupt occurs during
734 // makefile processing, the current target being made may be deleted
735 // without prompting (the same as command line -e option).
736 /* clang-format off */
742 /* clang-format on */
744 if (this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE")) {
745 /* clang-format off */
747 << "# Produce verbose output by default.\n"
750 /* clang-format on */
752 if (this->IsWatcomWMake()) {
753 /* clang-format off */
760 /* clang-format on */
762 makefileStream << "# Command-line flag to silence nested $(MAKE).\n"
763 "$(VERBOSE)MAKESILENT = -s\n"
766 // Write special target to silence make output. This must be after
767 // the default target in case VERBOSE is set (which changes the
768 // name). The setting of CMAKE_VERBOSE_MAKEFILE to ON will cause a
769 // "VERBOSE=1" to be added as a make variable which will change the
770 // name of this special target. This gives a make-time choice to
772 // Write directly to the stream since WriteMakeRule escapes '$'.
773 makefileStream << "#Suppress display of executed commands.\n"
774 "$(VERBOSE).SILENT:\n"
778 // Work-around for makes that drop rules that have no dependencies
780 cmGlobalUnixMakefileGenerator3* gg =
781 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
782 std::string hack = gg->GetEmptyRuleHackDepends();
784 no_depends.push_back(std::move(hack));
786 std::string hack_cmd = gg->GetEmptyRuleHackCommand();
787 if (!hack_cmd.empty()) {
788 no_commands.push_back(std::move(hack_cmd));
791 // Special symbolic target that never exists to force dependers to
793 this->WriteMakeRule(makefileStream, "A target that is always out of date.",
794 "cmake_force", no_depends, no_commands, true);
796 // Variables for reference by other rules.
797 this->WriteMakeVariables(makefileStream);
800 void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom(
801 std::ostream& makefileStream)
803 this->WriteDivider(makefileStream);
804 makefileStream << "# Special targets to cleanup operation of make.\n"
807 // Write special "cmake_check_build_system" target to run cmake with
808 // the --check-build-system flag.
809 if (!this->GlobalGenerator->GlobalSettingIsOn(
810 "CMAKE_SUPPRESS_REGENERATION")) {
811 // Build command to run CMake to check if anything needs regenerating.
812 std::vector<std::string> commands;
813 cmake* cm = this->GlobalGenerator->GetCMakeInstance();
814 if (cm->DoWriteGlobVerifyTarget()) {
815 std::string rescanRule =
816 cmStrCat("$(CMAKE_COMMAND) -P ",
817 this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
818 cmOutputConverter::SHELL));
819 commands.push_back(rescanRule);
821 std::string cmakefileName = "CMakeFiles/Makefile.cmake";
822 std::string runRule = cmStrCat(
823 "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
824 "--check-build-system ",
825 this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
828 std::vector<std::string> no_depends;
829 commands.push_back(std::move(runRule));
830 if (!this->IsRootMakefile()) {
831 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
832 this->GetCurrentBinaryDirectory());
834 this->WriteMakeRule(makefileStream,
835 "Special rule to run CMake to check the build system "
837 "No rule that depends on this can have "
838 "commands that come from listfiles\n"
839 "because they might be regenerated.",
840 "cmake_check_build_system", no_depends, commands,
845 void cmLocalUnixMakefileGenerator3::WriteConvenienceRule(
846 std::ostream& ruleFileStream, const std::string& realTarget,
847 const std::string& helpTarget)
849 // A rule is only needed if the names are different.
850 if (realTarget != helpTarget) {
851 // The helper target depends on the real target.
852 std::vector<std::string> depends;
853 depends.push_back(realTarget);
855 // There are no commands.
856 std::vector<std::string> no_commands;
859 this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
860 helpTarget, depends, no_commands, true);
864 std::string cmLocalUnixMakefileGenerator3::GetRelativeTargetDirectory(
865 cmGeneratorTarget const* target) const
868 cmStrCat(this->HomeRelativeOutputPath, this->GetTargetDirectory(target));
872 void cmLocalUnixMakefileGenerator3::AppendFlags(
873 std::string& flags, const std::string& newFlags) const
875 if (this->IsWatcomWMake() && !newFlags.empty()) {
876 std::string newf = newFlags;
877 if (newf.find("\\\"") != std::string::npos) {
878 cmSystemTools::ReplaceString(newf, "\\\"", "\"");
879 this->cmLocalGenerator::AppendFlags(flags, newf);
883 this->cmLocalGenerator::AppendFlags(flags, newFlags);
886 void cmLocalUnixMakefileGenerator3::AppendRuleDepend(
887 std::vector<std::string>& depends, const char* ruleFileName)
889 // Add a dependency on the rule file itself unless an option to skip
890 // it is specifically enabled by the user or project.
891 cmValue nodep = this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY");
892 if (cmIsOff(nodep)) {
893 depends.emplace_back(ruleFileName);
897 void cmLocalUnixMakefileGenerator3::AppendRuleDepends(
898 std::vector<std::string>& depends, std::vector<std::string> const& ruleFiles)
900 // Add a dependency on the rule file itself unless an option to skip
901 // it is specifically enabled by the user or project.
902 if (!this->Makefile->IsOn("CMAKE_SKIP_RULE_DEPENDENCY")) {
903 cm::append(depends, ruleFiles);
907 void cmLocalUnixMakefileGenerator3::AppendCustomDepends(
908 std::vector<std::string>& depends, const std::vector<cmCustomCommand>& ccs)
910 for (cmCustomCommand const& cc : ccs) {
911 cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
912 this->AppendCustomDepend(depends, ccg);
916 void cmLocalUnixMakefileGenerator3::AppendCustomDepend(
917 std::vector<std::string>& depends, cmCustomCommandGenerator const& ccg)
919 for (std::string const& d : ccg.GetDepends()) {
920 // Lookup the real name of the dependency in case it is a CMake target.
922 if (this->GetRealDependency(d, this->GetConfigName(), dep)) {
923 depends.push_back(std::move(dep));
928 void cmLocalUnixMakefileGenerator3::AppendCustomCommands(
929 std::vector<std::string>& commands, const std::vector<cmCustomCommand>& ccs,
930 cmGeneratorTarget* target, std::string const& relative)
932 for (cmCustomCommand const& cc : ccs) {
933 cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
934 this->AppendCustomCommand(commands, ccg, target, relative, true);
938 void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
939 std::vector<std::string>& commands, cmCustomCommandGenerator const& ccg,
940 cmGeneratorTarget* target, std::string const& relative, bool echo_comment,
941 std::ostream* content)
943 // Optionally create a command to display the custom command's
944 // comment text. This is used for pre-build, pre-link, and
945 // post-build command comments. Custom build step commands have
946 // their comments generated elsewhere.
948 const char* comment = ccg.GetComment();
949 if (comment && *comment) {
950 this->AppendEcho(commands, comment,
951 cmLocalUnixMakefileGenerator3::EchoGenerate);
955 // if the command specified a working directory use it.
956 std::string dir = this->GetCurrentBinaryDirectory();
957 std::string workingDir = ccg.GetWorkingDirectory();
958 if (!workingDir.empty()) {
965 std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
966 this->CreateRulePlaceholderExpander());
968 // Add each command line to the set of commands.
969 std::vector<std::string> commands1;
970 for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
971 // Build the command line in a single string.
972 std::string cmd = ccg.GetCommand(c);
974 // Use "call " before any invocations of .bat or .cmd files
975 // invoked as custom commands in the WindowsShell.
977 bool useCall = false;
979 if (this->IsWindowsShell()) {
981 if (cmd.size() > 4) {
982 suffix = cmSystemTools::LowerCase(cmd.substr(cmd.size() - 4));
983 if (suffix == ".bat" || suffix == ".cmd") {
989 cmSystemTools::ReplaceString(cmd, "/./", "/");
990 // Convert the command to a relative path only if the current
991 // working directory will be the start-output directory.
992 bool had_slash = cmd.find('/') != std::string::npos;
993 if (workingDir.empty()) {
994 cmd = this->MaybeRelativeToCurBinDir(cmd);
996 bool has_slash = cmd.find('/') != std::string::npos;
997 if (had_slash && !has_slash) {
998 // This command was specified as a path to a file in the
999 // current directory. Add a leading "./" so it can run
1000 // without the current directory being in the search path.
1001 cmd = cmStrCat("./", cmd);
1004 std::string launcher;
1005 // Short-circuit if there is no launcher.
1006 cmValue val = this->GetRuleLauncher(target, "RULE_LAUNCH_CUSTOM");
1007 if (cmNonempty(val)) {
1008 // Expand rule variables referenced in the given launcher command.
1009 cmRulePlaceholderExpander::RuleVariables vars;
1010 vars.CMTargetName = target->GetName().c_str();
1012 cmState::GetTargetTypeName(target->GetType()).c_str();
1014 const std::vector<std::string>& outputs = ccg.GetOutputs();
1015 if (!outputs.empty()) {
1016 output = outputs[0];
1017 if (workingDir.empty()) {
1018 output = this->MaybeRelativeToCurBinDir(output);
1021 this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
1023 vars.Output = output.c_str();
1026 rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
1027 if (!launcher.empty()) {
1032 std::string shellCommand = this->MaybeConvertWatcomShellCommand(cmd);
1033 if (shellCommand.empty()) {
1035 this->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
1037 cmd = launcher + shellCommand;
1039 ccg.AppendArguments(c, cmd);
1041 // Rule content does not include the launcher.
1042 *content << (cmd.c_str() + launcher.size());
1044 if (this->BorlandMakeCurlyHack) {
1045 // Borland Make has a very strange bug. If the first curly
1046 // brace anywhere in the command string is a left curly, it
1047 // must be written {{} instead of just {. Otherwise some
1048 // curly braces are removed. The hack can be skipped if the
1049 // first curly brace is the last character.
1050 std::string::size_type lcurly = cmd.find('{');
1051 if (lcurly != std::string::npos && lcurly < (cmd.size() - 1)) {
1052 std::string::size_type rcurly = cmd.find('}');
1053 if (rcurly == std::string::npos || rcurly > lcurly) {
1054 // The first curly is a left curly. Use the hack.
1056 cmStrCat(cmd.substr(0, lcurly), "{{}", cmd.substr(lcurly + 1));
1060 if (launcher.empty()) {
1062 cmd = cmStrCat("call ", cmd);
1063 } else if (this->IsNMake() && cmd[0] == '"') {
1064 cmd = cmStrCat("echo >nul && ", cmd);
1067 commands1.push_back(std::move(cmd));
1071 // Setup the proper working directory for the commands.
1072 this->CreateCDCommand(commands1, dir, relative);
1074 // push back the custom commands
1075 cm::append(commands, commands1);
1078 void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
1079 std::vector<std::string>& commands, const std::set<std::string>& files,
1080 cmGeneratorTarget* target, const char* filename)
1082 std::string currentBinDir = this->GetCurrentBinaryDirectory();
1083 std::string cleanfile = cmStrCat(
1084 currentBinDir, '/', this->GetTargetDirectory(target), "/cmake_clean");
1087 cleanfile += filename;
1089 cleanfile += ".cmake";
1090 cmsys::ofstream fout(cleanfile.c_str());
1092 cmSystemTools::Error("Could not create " + cleanfile);
1094 if (!files.empty()) {
1095 fout << "file(REMOVE_RECURSE\n";
1096 for (std::string const& file : files) {
1097 std::string fc = this->MaybeRelativeToCurBinDir(file);
1098 fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
1103 std::string remove = cmStrCat(
1104 "$(CMAKE_COMMAND) -P ",
1105 this->ConvertToOutputFormat(this->MaybeRelativeToCurBinDir(cleanfile),
1106 cmOutputConverter::SHELL));
1107 commands.push_back(std::move(remove));
1110 // For the main clean rule add per-language cleaning.
1112 // Get the set of source languages in the target.
1113 std::set<std::string> languages;
1114 target->GetLanguages(
1115 languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
1116 /* clang-format off */
1118 << "# Per-language clean rules from dependency scanning.\n"
1119 << "foreach(lang " << cmJoin(languages, " ") << ")\n"
1120 << " include(" << this->GetTargetDirectory(target)
1121 << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
1122 << "endforeach()\n";
1123 /* clang-format on */
1127 void cmLocalUnixMakefileGenerator3::AppendDirectoryCleanCommand(
1128 std::vector<std::string>& commands)
1130 std::vector<std::string> cleanFiles;
1131 // Look for additional files registered for cleaning in this directory.
1132 if (cmValue prop_value =
1133 this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
1134 cmExpandList(cmGeneratorExpression::Evaluate(
1136 this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")),
1139 if (cleanFiles.empty()) {
1143 const auto& rootLG = this->GetGlobalGenerator()->GetLocalGenerators().at(0);
1144 std::string const& currentBinaryDir = this->GetCurrentBinaryDirectory();
1145 std::string cleanfile =
1146 cmStrCat(currentBinaryDir, "/CMakeFiles/cmake_directory_clean.cmake");
1147 // Write clean script
1149 cmsys::ofstream fout(cleanfile.c_str());
1151 cmSystemTools::Error("Could not create " + cleanfile);
1154 fout << "file(REMOVE_RECURSE\n";
1155 for (std::string const& cfl : cleanFiles) {
1156 std::string fc = rootLG->MaybeRelativeToCurBinDir(
1157 cmSystemTools::CollapseFullPath(cfl, currentBinaryDir));
1158 fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
1164 std::string remove = cmStrCat(
1165 "$(CMAKE_COMMAND) -P ",
1166 this->ConvertToOutputFormat(rootLG->MaybeRelativeToCurBinDir(cleanfile),
1167 cmOutputConverter::SHELL));
1168 commands.push_back(std::move(remove));
1172 void cmLocalUnixMakefileGenerator3::AppendEcho(
1173 std::vector<std::string>& commands, std::string const& text, EchoColor color,
1174 EchoProgress const* progress)
1176 // Choose the color for the text.
1177 std::string color_name;
1178 if (this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile) {
1179 // See cmake::ExecuteEchoColor in cmake.cxx for these options.
1180 // This color set is readable on both black and white backgrounds.
1185 color_name = "--magenta --bold ";
1188 color_name = "--green ";
1191 color_name = "--green --bold ";
1194 color_name = "--blue --bold ";
1197 color_name = "--cyan ";
1202 // Echo one line at a time.
1205 for (const char* c = text.c_str();; ++c) {
1206 if (*c == '\n' || *c == '\0') {
1207 // Avoid writing a blank last line on end-of-string.
1208 if (*c != '\0' || !line.empty()) {
1209 // Add a command to echo this line.
1211 if (color_name.empty() && !progress) {
1212 // Use the native echo command.
1213 cmd = cmStrCat("@echo ", this->EscapeForShell(line, false, true));
1215 // Use cmake to echo the text in color.
1217 "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ",
1220 cmd += "--progress-dir=";
1221 cmd += this->ConvertToOutputFormat(progress->Dir,
1222 cmOutputConverter::SHELL);
1224 cmd += "--progress-num=";
1225 cmd += progress->Arg;
1228 cmd += this->EscapeForShell(line);
1230 commands.push_back(std::move(cmd));
1233 // Reset the line to empty.
1236 // Progress appears only on first line.
1239 // Terminate on end-of-string.
1243 } else if (*c != '\r') {
1244 // Append this character to the current line.
1250 std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
1251 std::string const& s, std::string const& s2)
1253 std::string unmodified = cmStrCat(s, s2);
1254 // if there is no restriction on the length of make variables
1255 // and there are no "." characters in the string, then return the
1256 // unmodified combination.
1257 if ((!this->MakefileVariableSize &&
1258 unmodified.find('.') == std::string::npos) &&
1259 (!this->MakefileVariableSize &&
1260 unmodified.find('+') == std::string::npos) &&
1261 (!this->MakefileVariableSize &&
1262 unmodified.find('-') == std::string::npos)) {
1266 // see if the variable has been defined before and return
1267 // the modified version of the variable
1268 auto i = this->MakeVariableMap.find(unmodified);
1269 if (i != this->MakeVariableMap.end()) {
1272 // start with the unmodified variable
1273 std::string ret = unmodified;
1274 // if this there is no value for this->MakefileVariableSize then
1275 // the string must have bad characters in it
1276 if (!this->MakefileVariableSize) {
1277 std::replace(ret.begin(), ret.end(), '.', '_');
1278 cmSystemTools::ReplaceString(ret, "-", "__");
1279 cmSystemTools::ReplaceString(ret, "+", "___");
1282 // make sure the _ version is not already used, if
1283 // it is used then add number to the end of the variable
1284 while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
1286 snprintf(buffer, sizeof(buffer), "%04d", ni);
1287 ret = unmodified + buffer;
1289 this->ShortMakeVariableMap[ret] = "1";
1290 this->MakeVariableMap[unmodified] = ret;
1294 // if the string is greater than 32 chars it is an invalid variable name
1296 if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
1297 int keep = this->MakefileVariableSize - 8;
1298 int size = keep + 3;
1299 std::string str1 = s;
1300 std::string str2 = s2;
1301 // we must shorten the combined string by 4 characters
1302 // keep no more than 24 characters from the second string
1303 if (static_cast<int>(str2.size()) > keep) {
1304 str2 = str2.substr(0, keep);
1306 if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
1307 str1 = str1.substr(0, size - str2.size());
1311 snprintf(buffer, sizeof(buffer), "%04d", ni);
1312 ret = str1 + str2 + buffer;
1313 while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
1315 snprintf(buffer, sizeof(buffer), "%04d", ni);
1316 ret = str1 + str2 + buffer;
1319 cmSystemTools::Error("Borland makefile variable length too long");
1322 // once an unused variable is found
1323 this->ShortMakeVariableMap[ret] = "1";
1325 // always make an entry into the unmodified to variable map
1326 this->MakeVariableMap[unmodified] = ret;
1330 bool cmLocalUnixMakefileGenerator3::UpdateDependencies(
1331 const std::string& tgtInfo, bool verbose, bool color)
1333 // read in the target info file
1334 if (!this->Makefile->ReadListFile(tgtInfo) ||
1335 cmSystemTools::GetErrorOccurredFlag()) {
1336 cmSystemTools::Error("Target DependInfo.cmake file not found");
1341 // Check if any multiple output pairs have a missing file.
1342 this->CheckMultipleOutputs(verbose);
1344 std::string const targetDir = cmSystemTools::GetFilenamePath(tgtInfo);
1345 if (!this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES").empty()) {
1346 // dependencies are managed by CMake itself
1348 std::string const internalDependFile = targetDir + "/depend.internal";
1349 std::string const dependFile = targetDir + "/depend.make";
1351 // If the target DependInfo.cmake file has changed since the last
1352 // time dependencies were scanned then force rescanning. This may
1353 // happen when a new source file is added and CMake regenerates the
1354 // project but no other sources were touched.
1355 bool needRescanDependInfo = false;
1356 cmFileTimeCache* ftc =
1357 this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache();
1360 if (!ftc->Compare(internalDependFile, tgtInfo, &result) || result < 0) {
1362 cmSystemTools::Stdout(cmStrCat("Dependee \"", tgtInfo,
1363 "\" is newer than depender \"",
1364 internalDependFile, "\".\n"));
1366 needRescanDependInfo = true;
1370 // If the directory information is newer than depend.internal, include
1371 // dirs may have changed. In this case discard all old dependencies.
1372 bool needRescanDirInfo = false;
1374 std::string dirInfoFile =
1375 cmStrCat(this->GetCurrentBinaryDirectory(),
1376 "/CMakeFiles/CMakeDirectoryInformation.cmake");
1378 if (!ftc->Compare(internalDependFile, dirInfoFile, &result) ||
1381 cmSystemTools::Stdout(cmStrCat("Dependee \"", dirInfoFile,
1382 "\" is newer than depender \"",
1383 internalDependFile, "\".\n"));
1385 needRescanDirInfo = true;
1389 // Check the implicit dependencies to see if they are up to date.
1390 // The build.make file may have explicit dependencies for the object
1391 // files but these will not affect the scanning process so they need
1392 // not be considered.
1393 cmDepends::DependencyMap validDependencies;
1394 bool needRescanDependencies = false;
1395 if (!needRescanDirInfo) {
1397 checker.SetVerbose(verbose);
1398 checker.SetFileTimeCache(ftc);
1399 // cmDependsC::Check() fills the vector validDependencies() with the
1400 // dependencies for those files where they are still valid, i.e.
1401 // neither the files themselves nor any files they depend on have
1402 // changed. We don't do that if the CMakeDirectoryInformation.cmake
1403 // file has changed, because then potentially all dependencies have
1404 // changed. This information is given later on to cmDependsC, which
1405 // then only rescans the files where it did not get valid dependencies
1406 // via this dependency vector. This means that in the normal case, when
1407 // only few or one file have been edited, then also only this one file
1408 // is actually scanned again, instead of all files for this target.
1409 needRescanDependencies =
1410 !checker.Check(dependFile, internalDependFile, validDependencies);
1413 if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
1414 // The dependencies must be regenerated.
1416 std::string targetName = cmSystemTools::GetFilenameName(targetDir);
1417 targetName = targetName.substr(0, targetName.length() - 4);
1418 std::string message =
1419 cmStrCat("Scanning dependencies of target ", targetName);
1420 cmSystemTools::MakefileColorEcho(
1421 cmsysTerminal_Color_ForegroundMagenta |
1422 cmsysTerminal_Color_ForegroundBold,
1423 message.c_str(), true, color);
1426 status = this->ScanDependencies(targetDir, dependFile,
1427 internalDependFile, validDependencies);
1432 this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_DEPENDENCY_FILES");
1433 if (!depends.empty()) {
1434 // dependencies are managed by compiler
1435 auto depFiles = cmExpandedList(depends, true);
1436 std::string const internalDepFile =
1437 targetDir + "/compiler_depend.internal";
1438 std::string const depFile = targetDir + "/compiler_depend.make";
1439 cmDepends::DependencyMap dependencies;
1440 cmDependsCompiler depsManager;
1441 bool projectOnly = cmIsOn(
1442 this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_IN_PROJECT_ONLY"));
1444 depsManager.SetVerbose(verbose);
1445 depsManager.SetLocalGenerator(this);
1447 if (!depsManager.CheckDependencies(
1448 internalDepFile, depFiles, dependencies,
1449 projectOnly ? NotInProjectDir(this->GetSourceDirectory(),
1450 this->GetBinaryDirectory())
1451 : std::function<bool(const std::string&)>())) {
1452 // regenerate dependencies files
1454 std::string targetName = cmCMakePath(targetDir)
1459 cmStrCat("Consolidate compiler generated dependencies of target ",
1461 cmSystemTools::MakefileColorEcho(
1462 cmsysTerminal_Color_ForegroundMagenta |
1463 cmsysTerminal_Color_ForegroundBold,
1464 message.c_str(), true, color);
1467 // Open the make depends file. This should be copy-if-different
1468 // because the make tool may try to reload it needlessly otherwise.
1469 cmGeneratedFileStream ruleFileStream(
1470 depFile, false, this->GlobalGenerator->GetMakefileEncoding());
1471 ruleFileStream.SetCopyIfDifferent(true);
1472 if (!ruleFileStream) {
1476 // Open the cmake dependency tracking file. This should not be
1477 // copy-if-different because dependencies are re-scanned when it is
1478 // older than the DependInfo.cmake.
1479 cmGeneratedFileStream internalRuleFileStream(
1480 internalDepFile, false, this->GlobalGenerator->GetMakefileEncoding());
1481 if (!internalRuleFileStream) {
1485 this->WriteDisclaimer(ruleFileStream);
1486 this->WriteDisclaimer(internalRuleFileStream);
1488 depsManager.WriteDependencies(dependencies, ruleFileStream,
1489 internalRuleFileStream);
1493 // The dependencies are already up-to-date.
1497 bool cmLocalUnixMakefileGenerator3::ScanDependencies(
1498 std::string const& targetDir, std::string const& dependFile,
1499 std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
1501 // Read the directory information file.
1502 cmMakefile* mf = this->Makefile;
1503 bool haveDirectoryInfo = false;
1505 std::string dirInfoFile =
1506 cmStrCat(this->GetCurrentBinaryDirectory(),
1507 "/CMakeFiles/CMakeDirectoryInformation.cmake");
1508 if (mf->ReadListFile(dirInfoFile) &&
1509 !cmSystemTools::GetErrorOccurredFlag()) {
1510 haveDirectoryInfo = true;
1514 // Lookup useful directory information.
1515 if (haveDirectoryInfo) {
1516 // Test whether we need to force Unix paths.
1517 if (cmValue force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
1518 if (!cmIsOff(force)) {
1519 cmSystemTools::SetForceUnixPaths(true);
1523 // Setup relative path top directories.
1524 cmValue relativePathTopSource =
1525 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE");
1526 cmValue relativePathTopBinary =
1527 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY");
1528 if (relativePathTopSource && relativePathTopBinary) {
1529 this->SetRelativePathTop(*relativePathTopSource, *relativePathTopBinary);
1532 cmSystemTools::Error("Directory Information file not found");
1535 // Open the make depends file. This should be copy-if-different
1536 // because the make tool may try to reload it needlessly otherwise.
1537 cmGeneratedFileStream ruleFileStream(
1538 dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
1539 ruleFileStream.SetCopyIfDifferent(true);
1540 if (!ruleFileStream) {
1544 // Open the cmake dependency tracking file. This should not be
1545 // copy-if-different because dependencies are re-scanned when it is
1546 // older than the DependInfo.cmake.
1547 cmGeneratedFileStream internalRuleFileStream(
1548 internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
1549 if (!internalRuleFileStream) {
1553 this->WriteDisclaimer(ruleFileStream);
1554 this->WriteDisclaimer(internalRuleFileStream);
1556 // for each language we need to scan, scan it
1557 std::vector<std::string> langs =
1558 cmExpandedList(mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"));
1559 for (std::string const& lang : langs) {
1560 // construct the checker
1561 // Create the scanner for this language
1562 std::unique_ptr<cmDepends> scanner;
1563 if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
1564 lang == "OBJC" || lang == "OBJCXX" || lang == "CUDA" ||
1565 lang == "HIP" || lang == "ISPC") {
1566 // TODO: Handle RC (resource files) dependencies correctly.
1567 scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
1569 #ifndef CMAKE_BOOTSTRAP
1570 else if (lang == "Fortran") {
1571 ruleFileStream << "# Note that incremental build could trigger "
1572 << "a call to cmake_copy_f90_mod on each re-build\n";
1573 scanner = cm::make_unique<cmDependsFortran>(this);
1574 } else if (lang == "Java") {
1575 scanner = cm::make_unique<cmDependsJava>();
1580 scanner->SetLocalGenerator(this);
1581 scanner->SetFileTimeCache(
1582 this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
1583 scanner->SetLanguage(lang);
1584 scanner->SetTargetDirectory(targetDir);
1585 scanner->Write(ruleFileStream, internalRuleFileStream);
1592 void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
1594 cmMakefile* mf = this->Makefile;
1596 // Get the string listing the multiple output pairs.
1597 cmValue pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
1598 if (!pairs_string) {
1602 // Convert the string to a list and preserve empty entries.
1603 std::vector<std::string> pairs = cmExpandedList(*pairs_string, true);
1604 for (auto i = pairs.begin(); i != pairs.end() && (i + 1) != pairs.end();) {
1605 const std::string& depender = *i++;
1606 const std::string& dependee = *i++;
1608 // If the depender is missing then delete the dependee to make
1609 // sure both will be regenerated.
1610 if (cmSystemTools::FileExists(dependee) &&
1611 !cmSystemTools::FileExists(depender)) {
1613 cmSystemTools::Stdout(cmStrCat(
1614 "Deleting primary custom command output \"", dependee,
1615 "\" because another output \"", depender, "\" does not exist.\n"));
1617 cmSystemTools::RemoveFile(dependee);
1622 void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
1623 std::ostream& ruleFileStream)
1625 this->WriteDisclaimer(ruleFileStream);
1627 // Write the main entry point target. This must be the VERY first
1628 // target so that make with no arguments will run it.
1630 // Just depend on the all target to drive the build.
1631 std::vector<std::string> depends;
1632 std::vector<std::string> no_commands;
1633 depends.emplace_back("all");
1636 this->WriteMakeRule(ruleFileStream,
1637 "Default target executed when no arguments are "
1639 "default_target", depends, no_commands, true);
1641 // Help out users that try "gmake target1 target2 -j".
1642 cmGlobalUnixMakefileGenerator3* gg =
1643 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
1644 if (gg->AllowNotParallel()) {
1645 std::vector<std::string> no_depends;
1646 this->WriteMakeRule(ruleFileStream,
1647 "Allow only one \"make -f "
1648 "Makefile2\" at a time, but pass "
1650 ".NOTPARALLEL", no_depends, no_commands, false);
1654 this->WriteSpecialTargetsTop(ruleFileStream);
1656 // Include the progress variables for the target.
1657 // Write all global targets
1658 this->WriteDivider(ruleFileStream);
1659 ruleFileStream << "# Targets provided globally by CMake.\n"
1661 const auto& targets = this->GetGeneratorTargets();
1662 for (const auto& gt : targets) {
1663 if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
1664 std::string targetString =
1665 "Special rule for the target " + gt->GetName();
1666 std::vector<std::string> commands;
1667 std::vector<std::string> depends;
1669 cmValue p = gt->GetProperty("EchoString");
1670 const char* text = p ? p->c_str() : "Running external command ...";
1671 depends.reserve(gt->GetUtilities().size());
1672 for (BT<std::pair<std::string, bool>> const& u : gt->GetUtilities()) {
1673 depends.push_back(u.Value.first);
1675 this->AppendEcho(commands, text,
1676 cmLocalUnixMakefileGenerator3::EchoGlobal);
1678 // Global targets store their rules in pre- and post-build commands.
1679 this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
1680 this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
1681 this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt.get(),
1682 this->GetCurrentBinaryDirectory());
1683 this->AppendCustomCommands(commands, gt->GetPostBuildCommands(),
1684 gt.get(), this->GetCurrentBinaryDirectory());
1685 std::string targetName = gt->GetName();
1686 this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
1687 depends, commands, true);
1689 // Provide a "/fast" version of the target.
1691 if ((targetName == "install") || (targetName == "install/local") ||
1692 (targetName == "install/strip")) {
1693 // Provide a fast install target that does not depend on all
1694 // but has the same command.
1695 depends.emplace_back("preinstall/fast");
1697 // Just forward to the real target so at least it will work.
1698 depends.push_back(targetName);
1701 targetName += "/fast";
1702 this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
1703 depends, commands, true);
1707 std::vector<std::string> depends;
1708 std::vector<std::string> commands;
1710 // Write the all rule.
1711 std::string recursiveTarget =
1712 cmStrCat(this->GetCurrentBinaryDirectory(), "/all");
1715 !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
1717 depends.emplace_back("cmake_check_build_system");
1720 std::string progressDir =
1721 cmStrCat(this->GetBinaryDirectory(), "/CMakeFiles");
1723 std::ostringstream progCmd;
1724 progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
1725 progCmd << this->ConvertToOutputFormat(progressDir,
1726 cmOutputConverter::SHELL);
1728 std::string progressFile = "/CMakeFiles/progress.marks";
1729 std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
1731 << this->ConvertToOutputFormat(progressFileNameFull,
1732 cmOutputConverter::SHELL);
1733 commands.push_back(progCmd.str());
1735 std::string mf2Dir = "CMakeFiles/Makefile2";
1736 commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1737 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1738 this->GetCurrentBinaryDirectory());
1740 std::ostringstream progCmd;
1741 progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
1742 progCmd << this->ConvertToOutputFormat(progressDir,
1743 cmOutputConverter::SHELL);
1745 commands.push_back(progCmd.str());
1747 this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
1750 // Write the clean rule.
1751 recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/clean");
1754 commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1755 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1756 this->GetCurrentBinaryDirectory());
1757 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
1758 depends, commands, true);
1761 depends.emplace_back("clean");
1762 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
1763 depends, commands, true);
1765 // Write the preinstall rule.
1766 recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/preinstall");
1770 this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
1771 if (cmIsOff(noall)) {
1772 // Drive the build before installing.
1773 depends.emplace_back("all");
1774 } else if (regenerate) {
1775 // At least make sure the build system is up to date.
1776 depends.emplace_back("cmake_check_build_system");
1778 commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1779 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1780 this->GetCurrentBinaryDirectory());
1781 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1782 "preinstall", depends, commands, true);
1784 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1785 "preinstall/fast", depends, commands, true);
1788 // write the depend rule, really a recompute depends rule
1791 cmake* cm = this->GlobalGenerator->GetCMakeInstance();
1792 if (cm->DoWriteGlobVerifyTarget()) {
1793 std::string rescanRule =
1794 cmStrCat("$(CMAKE_COMMAND) -P ",
1795 this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
1796 cmOutputConverter::SHELL));
1797 commands.push_back(rescanRule);
1799 std::string cmakefileName = "CMakeFiles/Makefile.cmake";
1801 std::string runRule = cmStrCat(
1802 "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
1803 "--check-build-system ",
1804 this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
1806 commands.push_back(std::move(runRule));
1808 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1809 this->GetCurrentBinaryDirectory());
1810 this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
1815 void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
1818 // Get the list of target files to check
1819 cmValue infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
1823 std::vector<std::string> files = cmExpandedList(*infoDef);
1825 // Each depend information file corresponds to a target. Clear the
1826 // dependencies for that target.
1828 clearer.SetVerbose(verbose);
1829 for (std::string const& file : files) {
1830 auto snapshot = mf->GetState()->CreateBaseSnapshot();
1831 cmMakefile lmf(mf->GetGlobalGenerator(), snapshot);
1832 lmf.ReadListFile(file);
1834 if (!lmf.GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES").empty()) {
1835 std::string dir = cmSystemTools::GetFilenamePath(file);
1837 // Clear the implicit dependency makefile.
1838 std::string dependFile = dir + "/depend.make";
1839 clearer.Clear(dependFile);
1841 // Remove the internal dependency check file to force
1843 std::string internalDependFile = dir + "/depend.internal";
1844 cmSystemTools::RemoveFile(internalDependFile);
1847 auto depsFiles = lmf.GetSafeDefinition("CMAKE_DEPENDS_DEPENDENCY_FILES");
1848 if (!depsFiles.empty()) {
1849 auto dir = cmCMakePath(file).GetParentPath();
1850 // Clear the implicit dependency makefile.
1851 auto depFile = cmCMakePath(dir).Append("compiler_depend.make");
1852 clearer.Clear(depFile.GenericString());
1854 // Remove the internal dependency check file
1855 auto internalDepFile =
1856 cmCMakePath(dir).Append("compiler_depend.internal");
1857 cmSystemTools::RemoveFile(internalDepFile.GenericString());
1859 // Touch timestamp file to force dependencies regeneration
1860 auto DepTimestamp = cmCMakePath(dir).Append("compiler_depend.ts");
1861 cmSystemTools::Touch(DepTimestamp.GenericString(), true);
1863 // clear the dependencies files generated by the compiler
1864 std::vector<std::string> dependencies = cmExpandedList(depsFiles, true);
1865 cmDependsCompiler depsManager;
1866 depsManager.SetVerbose(verbose);
1867 depsManager.ClearDependencies(dependencies);
1872 void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
1873 std::ostream& cmakefileStream, cmGeneratorTarget* target)
1875 // To enable dependencies filtering
1876 cmakefileStream << "\n"
1877 << "# Consider dependencies only in project.\n"
1878 << "set(CMAKE_DEPENDS_IN_PROJECT_ONLY "
1879 << (cmIsOn(this->Makefile->GetSafeDefinition(
1880 "CMAKE_DEPENDS_IN_PROJECT_ONLY"))
1885 auto const& implicitLangs =
1886 this->GetImplicitDepends(target, cmDependencyScannerKind::CMake);
1888 // list the languages
1889 cmakefileStream << "# The set of languages for which implicit "
1890 "dependencies are needed:\n";
1891 cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
1892 for (auto const& implicitLang : implicitLangs) {
1893 cmakefileStream << " \"" << implicitLang.first << "\"\n";
1895 cmakefileStream << " )\n";
1897 if (!implicitLangs.empty()) {
1898 // now list the files for each language
1900 << "# The set of files for implicit dependencies of each language:\n";
1901 for (auto const& implicitLang : implicitLangs) {
1902 const auto& lang = implicitLang.first;
1904 cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << lang << "\n";
1905 auto const& implicitPairs = implicitLang.second;
1907 // for each file pair
1908 for (auto const& implicitPair : implicitPairs) {
1909 for (auto const& di : implicitPair.second) {
1910 cmakefileStream << " \"" << di << "\" ";
1911 cmakefileStream << "\"" << implicitPair.first << "\"\n";
1914 cmakefileStream << " )\n";
1916 // Tell the dependency scanner what compiler is used.
1917 std::string cidVar = cmStrCat("CMAKE_", lang, "_COMPILER_ID");
1918 cmValue cid = this->Makefile->GetDefinition(cidVar);
1919 if (cmNonempty(cid)) {
1920 cmakefileStream << "set(CMAKE_" << lang << "_COMPILER_ID \"" << *cid
1924 if (lang == "Fortran") {
1925 std::string smodSep =
1926 this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
1927 std::string smodExt =
1928 this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
1929 cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_SEP \"" << smodSep
1931 cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_EXT \"" << smodExt
1935 // Build a list of preprocessor definitions for the target.
1936 std::set<std::string> defines;
1937 this->GetTargetDefines(target, this->GetConfigName(), lang, defines);
1938 if (!defines.empty()) {
1939 /* clang-format off */
1942 << "# Preprocessor definitions for this target.\n"
1943 << "set(CMAKE_TARGET_DEFINITIONS_" << lang << "\n";
1944 /* clang-format on */
1945 for (std::string const& define : defines) {
1946 cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define)
1949 cmakefileStream << " )\n";
1952 // Target-specific include directories:
1953 cmakefileStream << "\n"
1954 << "# The include file search paths:\n";
1955 cmakefileStream << "set(CMAKE_" << lang << "_TARGET_INCLUDE_PATH\n";
1956 std::vector<std::string> includes;
1958 this->GetIncludeDirectories(includes, target, lang,
1959 this->GetConfigName());
1960 std::string const& binaryDir = this->GetState()->GetBinaryDirectory();
1961 if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
1962 std::string const& sourceDir = this->GetState()->GetSourceDirectory();
1963 cm::erase_if(includes, ::NotInProjectDir(sourceDir, binaryDir));
1965 for (std::string const& include : includes) {
1966 cmakefileStream << " \"" << this->MaybeRelativeToTopBinDir(include)
1969 cmakefileStream << " )\n";
1972 // Store include transform rule properties. Write the directory
1973 // rules first because they may be overridden by later target rules.
1974 std::vector<std::string> transformRules;
1976 this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
1977 cmExpandList(*xform, transformRules);
1980 target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
1981 cmExpandList(*xform, transformRules);
1983 if (!transformRules.empty()) {
1984 cmakefileStream << "\nset(CMAKE_INCLUDE_TRANSFORMS\n";
1985 for (std::string const& tr : transformRules) {
1986 cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr)
1989 cmakefileStream << " )\n";
1993 auto const& compilerLangs =
1994 this->GetImplicitDepends(target, cmDependencyScannerKind::Compiler);
1996 // list the dependency files managed by the compiler
1997 cmakefileStream << "\n# The set of dependency files which are needed:\n";
1998 cmakefileStream << "set(CMAKE_DEPENDS_DEPENDENCY_FILES\n";
1999 for (auto const& compilerLang : compilerLangs) {
2000 auto const& compilerPairs = compilerLang.second;
2001 if (compilerLang.first == "CUSTOM"_s) {
2002 for (auto const& compilerPair : compilerPairs) {
2003 for (auto const& src : compilerPair.second) {
2004 cmakefileStream << R"( "" ")"
2005 << this->MaybeRelativeToTopBinDir(compilerPair.first)
2006 << R"(" "custom" ")"
2007 << this->MaybeRelativeToTopBinDir(src) << "\"\n";
2011 auto depFormat = this->Makefile->GetSafeDefinition(
2012 cmStrCat("CMAKE_", compilerLang.first, "_DEPFILE_FORMAT"));
2013 for (auto const& compilerPair : compilerPairs) {
2014 for (auto const& src : compilerPair.second) {
2015 cmakefileStream << " \"" << src << "\" \""
2016 << this->MaybeRelativeToTopBinDir(compilerPair.first)
2017 << "\" \"" << depFormat << "\" \""
2018 << this->MaybeRelativeToTopBinDir(compilerPair.first)
2024 cmakefileStream << " )\n";
2027 void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
2029 os << "# CMAKE generated file: DO NOT EDIT!\n"
2030 << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
2031 << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
2032 << cmVersion::GetMinorVersion() << "\n\n";
2035 std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
2036 const std::string& makefile, const std::string& tgt)
2038 // Call make on the given file.
2039 std::string cmd = cmStrCat(
2040 "$(MAKE) $(MAKESILENT) -f ",
2041 this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL), ' ');
2043 cmGlobalUnixMakefileGenerator3* gg =
2044 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
2045 // Pass down verbosity level.
2046 if (!gg->MakeSilentFlag.empty()) {
2047 cmd += gg->MakeSilentFlag;
2051 // Most unix makes will pass the command line flags to make down to
2052 // sub-invoked makes via an environment variable. However, some
2053 // makes do not support that, so you have to pass the flags
2055 if (gg->PassMakeflags) {
2056 cmd += "-$(MAKEFLAGS) ";
2061 // The make target is always relative to the top of the build tree.
2062 std::string tgt2 = this->MaybeRelativeToTopBinDir(tgt);
2064 // The target may have been written with windows paths.
2065 cmSystemTools::ConvertToOutputSlashes(tgt2);
2067 // Escape one extra time if the make tool requires it.
2068 if (this->MakeCommandEscapeTargetTwice) {
2069 tgt2 = this->EscapeForShell(tgt2, true, false);
2072 // The target name is now a string that should be passed verbatim
2073 // on the command line.
2074 cmd += this->EscapeForShell(tgt2, true, false);
2079 void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
2081 os << "#======================================"
2082 "=======================================\n";
2085 void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
2086 const std::string& s)
2088 // Write the given string to the stream with escaping to get it back
2089 // into CMake through the lexical scanner.
2094 } else if (c == '"') {
2103 std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
2104 const std::string& p, bool useWatcomQuote)
2106 // Split the path into its components.
2107 std::vector<std::string> components;
2108 cmSystemTools::SplitPath(p, components);
2110 // Open the quoted result.
2112 if (useWatcomQuote) {
2113 #if defined(_WIN32) && !defined(__CYGWIN__)
2122 // Return an empty path if there are no components.
2123 if (!components.empty()) {
2124 // Choose a slash direction and fix root component.
2125 const char* slash = "/";
2126 #if defined(_WIN32) && !defined(__CYGWIN__)
2127 if (!cmSystemTools::GetForceUnixPaths()) {
2129 for (char& i : components[0]) {
2137 // Begin the quoted result with the root component.
2138 result += components[0];
2140 if (components.size() > 1) {
2141 // Now add the rest of the components separated by the proper slash
2142 // direction for this platform.
2143 auto compEnd = std::remove(components.begin() + 1, components.end() - 1,
2145 auto compStart = components.begin() + 1;
2146 result += cmJoin(cmMakeRange(compStart, compEnd), slash);
2147 // Only the last component can be empty to avoid double slashes.
2149 result += components.back();
2153 // Close the quoted result.
2154 if (useWatcomQuote) {
2155 #if defined(_WIN32) && !defined(__CYGWIN__)
2167 std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
2168 cmGeneratorTarget const* target) const
2170 std::string dir = cmStrCat("CMakeFiles/", target->GetName());
2179 cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
2180 cmLocalUnixMakefileGenerator3::GetImplicitDepends(
2181 const cmGeneratorTarget* tgt, cmDependencyScannerKind scanner)
2183 return this->ImplicitDepends[tgt->GetName()][scanner];
2186 void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
2187 const cmGeneratorTarget* tgt, const std::string& lang,
2188 const std::string& obj, const std::string& src,
2189 cmDependencyScannerKind scanner)
2191 this->ImplicitDepends[tgt->GetName()][scanner][lang][obj].push_back(src);
2194 void cmLocalUnixMakefileGenerator3::CreateCDCommand(
2195 std::vector<std::string>& commands, std::string const& tgtDir,
2196 std::string const& relDir)
2198 // do we need to cd?
2199 if (tgtDir == relDir) {
2203 // In a Windows shell we must change drive letter too. The shell
2204 // used by NMake and Borland make does not support "cd /d" so this
2205 // feature simply cannot work with them (Borland make does not even
2206 // support changing the drive letter with just "d:").
2207 const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
2209 cmGlobalUnixMakefileGenerator3* gg =
2210 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
2212 // On Windows we must perform each step separately and then change
2213 // back because the shell keeps the working directory between
2216 cmStrCat(cd_cmd, this->ConvertToOutputForExisting(tgtDir));
2217 commands.insert(commands.begin(), cmd);
2219 // Change back to the starting directory.
2220 cmd = cmStrCat(cd_cmd, this->ConvertToOutputForExisting(relDir));
2221 commands.push_back(std::move(cmd));
2223 // On UNIX we must construct a single shell command to change
2224 // directory and build because make resets the directory between
2226 std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
2227 std::string prefix = cd_cmd + outputForExisting + " && ";
2228 std::transform(commands.begin(), commands.end(), commands.begin(),
2229 [&prefix](std::string const& s) { return prefix + s; });