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.
1415 std::string targetName = cmSystemTools::GetFilenameName(targetDir);
1416 targetName = targetName.substr(0, targetName.length() - 4);
1417 std::string message =
1418 cmStrCat("Scanning dependencies of target ", targetName);
1419 cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
1420 cmsysTerminal_Color_ForegroundBold,
1421 message.c_str(), true, color);
1423 status = this->ScanDependencies(targetDir, dependFile,
1424 internalDependFile, validDependencies);
1429 this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_DEPENDENCY_FILES");
1430 if (!depends.empty()) {
1431 // dependencies are managed by compiler
1432 auto depFiles = cmExpandedList(depends, true);
1433 std::string const internalDepFile =
1434 targetDir + "/compiler_depend.internal";
1435 std::string const depFile = targetDir + "/compiler_depend.make";
1436 cmDepends::DependencyMap dependencies;
1437 cmDependsCompiler depsManager;
1438 bool projectOnly = cmIsOn(
1439 this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_IN_PROJECT_ONLY"));
1441 depsManager.SetVerbose(verbose);
1442 depsManager.SetLocalGenerator(this);
1444 if (!depsManager.CheckDependencies(
1445 internalDepFile, depFiles, dependencies,
1446 projectOnly ? NotInProjectDir(this->GetSourceDirectory(),
1447 this->GetBinaryDirectory())
1448 : std::function<bool(const std::string&)>())) {
1449 // regenerate dependencies files
1450 std::string targetName =
1451 cmCMakePath(targetDir).GetFileName().RemoveExtension().GenericString();
1452 auto message = cmStrCat(
1453 "Consolidate compiler generated dependencies of target ", targetName);
1454 cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
1455 cmsysTerminal_Color_ForegroundBold,
1456 message.c_str(), true, color);
1458 // Open the make depends file. This should be copy-if-different
1459 // because the make tool may try to reload it needlessly otherwise.
1460 cmGeneratedFileStream ruleFileStream(
1461 depFile, false, this->GlobalGenerator->GetMakefileEncoding());
1462 ruleFileStream.SetCopyIfDifferent(true);
1463 if (!ruleFileStream) {
1467 // Open the cmake dependency tracking file. This should not be
1468 // copy-if-different because dependencies are re-scanned when it is
1469 // older than the DependInfo.cmake.
1470 cmGeneratedFileStream internalRuleFileStream(
1471 internalDepFile, false, this->GlobalGenerator->GetMakefileEncoding());
1472 if (!internalRuleFileStream) {
1476 this->WriteDisclaimer(ruleFileStream);
1477 this->WriteDisclaimer(internalRuleFileStream);
1479 depsManager.WriteDependencies(dependencies, ruleFileStream,
1480 internalRuleFileStream);
1484 // The dependencies are already up-to-date.
1488 bool cmLocalUnixMakefileGenerator3::ScanDependencies(
1489 std::string const& targetDir, std::string const& dependFile,
1490 std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
1492 // Read the directory information file.
1493 cmMakefile* mf = this->Makefile;
1494 bool haveDirectoryInfo = false;
1496 std::string dirInfoFile =
1497 cmStrCat(this->GetCurrentBinaryDirectory(),
1498 "/CMakeFiles/CMakeDirectoryInformation.cmake");
1499 if (mf->ReadListFile(dirInfoFile) &&
1500 !cmSystemTools::GetErrorOccurredFlag()) {
1501 haveDirectoryInfo = true;
1505 // Lookup useful directory information.
1506 if (haveDirectoryInfo) {
1507 // Test whether we need to force Unix paths.
1508 if (cmValue force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
1509 if (!cmIsOff(force)) {
1510 cmSystemTools::SetForceUnixPaths(true);
1514 // Setup relative path top directories.
1515 cmValue relativePathTopSource =
1516 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE");
1517 cmValue relativePathTopBinary =
1518 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY");
1519 if (relativePathTopSource && relativePathTopBinary) {
1520 this->SetRelativePathTop(*relativePathTopSource, *relativePathTopBinary);
1523 cmSystemTools::Error("Directory Information file not found");
1526 // Open the make depends file. This should be copy-if-different
1527 // because the make tool may try to reload it needlessly otherwise.
1528 cmGeneratedFileStream ruleFileStream(
1529 dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
1530 ruleFileStream.SetCopyIfDifferent(true);
1531 if (!ruleFileStream) {
1535 // Open the cmake dependency tracking file. This should not be
1536 // copy-if-different because dependencies are re-scanned when it is
1537 // older than the DependInfo.cmake.
1538 cmGeneratedFileStream internalRuleFileStream(
1539 internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
1540 if (!internalRuleFileStream) {
1544 this->WriteDisclaimer(ruleFileStream);
1545 this->WriteDisclaimer(internalRuleFileStream);
1547 // for each language we need to scan, scan it
1548 std::vector<std::string> langs =
1549 cmExpandedList(mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"));
1550 for (std::string const& lang : langs) {
1551 // construct the checker
1552 // Create the scanner for this language
1553 std::unique_ptr<cmDepends> scanner;
1554 if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
1555 lang == "OBJC" || lang == "OBJCXX" || lang == "CUDA" ||
1556 lang == "HIP" || lang == "ISPC") {
1557 // TODO: Handle RC (resource files) dependencies correctly.
1558 scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
1560 #ifndef CMAKE_BOOTSTRAP
1561 else if (lang == "Fortran") {
1562 ruleFileStream << "# Note that incremental build could trigger "
1563 << "a call to cmake_copy_f90_mod on each re-build\n";
1564 scanner = cm::make_unique<cmDependsFortran>(this);
1565 } else if (lang == "Java") {
1566 scanner = cm::make_unique<cmDependsJava>();
1571 scanner->SetLocalGenerator(this);
1572 scanner->SetFileTimeCache(
1573 this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
1574 scanner->SetLanguage(lang);
1575 scanner->SetTargetDirectory(targetDir);
1576 scanner->Write(ruleFileStream, internalRuleFileStream);
1583 void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
1585 cmMakefile* mf = this->Makefile;
1587 // Get the string listing the multiple output pairs.
1588 cmValue pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
1589 if (!pairs_string) {
1593 // Convert the string to a list and preserve empty entries.
1594 std::vector<std::string> pairs = cmExpandedList(*pairs_string, true);
1595 for (auto i = pairs.begin(); i != pairs.end() && (i + 1) != pairs.end();) {
1596 const std::string& depender = *i++;
1597 const std::string& dependee = *i++;
1599 // If the depender is missing then delete the dependee to make
1600 // sure both will be regenerated.
1601 if (cmSystemTools::FileExists(dependee) &&
1602 !cmSystemTools::FileExists(depender)) {
1604 cmSystemTools::Stdout(cmStrCat(
1605 "Deleting primary custom command output \"", dependee,
1606 "\" because another output \"", depender, "\" does not exist.\n"));
1608 cmSystemTools::RemoveFile(dependee);
1613 void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
1614 std::ostream& ruleFileStream)
1616 this->WriteDisclaimer(ruleFileStream);
1618 // Write the main entry point target. This must be the VERY first
1619 // target so that make with no arguments will run it.
1621 // Just depend on the all target to drive the build.
1622 std::vector<std::string> depends;
1623 std::vector<std::string> no_commands;
1624 depends.emplace_back("all");
1627 this->WriteMakeRule(ruleFileStream,
1628 "Default target executed when no arguments are "
1630 "default_target", depends, no_commands, true);
1632 // Help out users that try "gmake target1 target2 -j".
1633 cmGlobalUnixMakefileGenerator3* gg =
1634 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
1635 if (gg->AllowNotParallel()) {
1636 std::vector<std::string> no_depends;
1637 this->WriteMakeRule(ruleFileStream,
1638 "Allow only one \"make -f "
1639 "Makefile2\" at a time, but pass "
1641 ".NOTPARALLEL", no_depends, no_commands, false);
1645 this->WriteSpecialTargetsTop(ruleFileStream);
1647 // Include the progress variables for the target.
1648 // Write all global targets
1649 this->WriteDivider(ruleFileStream);
1650 ruleFileStream << "# Targets provided globally by CMake.\n"
1652 const auto& targets = this->GetGeneratorTargets();
1653 for (const auto& gt : targets) {
1654 if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
1655 std::string targetString =
1656 "Special rule for the target " + gt->GetName();
1657 std::vector<std::string> commands;
1658 std::vector<std::string> depends;
1660 cmValue p = gt->GetProperty("EchoString");
1661 const char* text = p ? p->c_str() : "Running external command ...";
1662 depends.reserve(gt->GetUtilities().size());
1663 for (BT<std::pair<std::string, bool>> const& u : gt->GetUtilities()) {
1664 depends.push_back(u.Value.first);
1666 this->AppendEcho(commands, text,
1667 cmLocalUnixMakefileGenerator3::EchoGlobal);
1669 // Global targets store their rules in pre- and post-build commands.
1670 this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
1671 this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
1672 this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt.get(),
1673 this->GetCurrentBinaryDirectory());
1674 this->AppendCustomCommands(commands, gt->GetPostBuildCommands(),
1675 gt.get(), this->GetCurrentBinaryDirectory());
1676 std::string targetName = gt->GetName();
1677 this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
1678 depends, commands, true);
1680 // Provide a "/fast" version of the target.
1682 if ((targetName == "install") || (targetName == "install/local") ||
1683 (targetName == "install/strip")) {
1684 // Provide a fast install target that does not depend on all
1685 // but has the same command.
1686 depends.emplace_back("preinstall/fast");
1688 // Just forward to the real target so at least it will work.
1689 depends.push_back(targetName);
1692 targetName += "/fast";
1693 this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
1694 depends, commands, true);
1698 std::vector<std::string> depends;
1699 std::vector<std::string> commands;
1701 // Write the all rule.
1702 std::string recursiveTarget =
1703 cmStrCat(this->GetCurrentBinaryDirectory(), "/all");
1706 !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
1708 depends.emplace_back("cmake_check_build_system");
1711 std::string progressDir =
1712 cmStrCat(this->GetBinaryDirectory(), "/CMakeFiles");
1714 std::ostringstream progCmd;
1715 progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
1716 progCmd << this->ConvertToOutputFormat(progressDir,
1717 cmOutputConverter::SHELL);
1719 std::string progressFile = "/CMakeFiles/progress.marks";
1720 std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
1722 << this->ConvertToOutputFormat(progressFileNameFull,
1723 cmOutputConverter::SHELL);
1724 commands.push_back(progCmd.str());
1726 std::string mf2Dir = "CMakeFiles/Makefile2";
1727 commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1728 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1729 this->GetCurrentBinaryDirectory());
1731 std::ostringstream progCmd;
1732 progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
1733 progCmd << this->ConvertToOutputFormat(progressDir,
1734 cmOutputConverter::SHELL);
1736 commands.push_back(progCmd.str());
1738 this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
1741 // Write the clean rule.
1742 recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/clean");
1745 commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1746 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1747 this->GetCurrentBinaryDirectory());
1748 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
1749 depends, commands, true);
1752 depends.emplace_back("clean");
1753 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
1754 depends, commands, true);
1756 // Write the preinstall rule.
1757 recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/preinstall");
1761 this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
1762 if (cmIsOff(noall)) {
1763 // Drive the build before installing.
1764 depends.emplace_back("all");
1765 } else if (regenerate) {
1766 // At least make sure the build system is up to date.
1767 depends.emplace_back("cmake_check_build_system");
1769 commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1770 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1771 this->GetCurrentBinaryDirectory());
1772 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1773 "preinstall", depends, commands, true);
1775 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1776 "preinstall/fast", depends, commands, true);
1779 // write the depend rule, really a recompute depends rule
1782 cmake* cm = this->GlobalGenerator->GetCMakeInstance();
1783 if (cm->DoWriteGlobVerifyTarget()) {
1784 std::string rescanRule =
1785 cmStrCat("$(CMAKE_COMMAND) -P ",
1786 this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
1787 cmOutputConverter::SHELL));
1788 commands.push_back(rescanRule);
1790 std::string cmakefileName = "CMakeFiles/Makefile.cmake";
1792 std::string runRule = cmStrCat(
1793 "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
1794 "--check-build-system ",
1795 this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
1797 commands.push_back(std::move(runRule));
1799 this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1800 this->GetCurrentBinaryDirectory());
1801 this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
1806 void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
1809 // Get the list of target files to check
1810 cmValue infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
1814 std::vector<std::string> files = cmExpandedList(*infoDef);
1816 // Each depend information file corresponds to a target. Clear the
1817 // dependencies for that target.
1819 clearer.SetVerbose(verbose);
1820 for (std::string const& file : files) {
1821 auto snapshot = mf->GetState()->CreateBaseSnapshot();
1822 cmMakefile lmf(mf->GetGlobalGenerator(), snapshot);
1823 lmf.ReadListFile(file);
1825 if (!lmf.GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES").empty()) {
1826 std::string dir = cmSystemTools::GetFilenamePath(file);
1828 // Clear the implicit dependency makefile.
1829 std::string dependFile = dir + "/depend.make";
1830 clearer.Clear(dependFile);
1832 // Remove the internal dependency check file to force
1834 std::string internalDependFile = dir + "/depend.internal";
1835 cmSystemTools::RemoveFile(internalDependFile);
1838 auto depsFiles = lmf.GetSafeDefinition("CMAKE_DEPENDS_DEPENDENCY_FILES");
1839 if (!depsFiles.empty()) {
1840 auto dir = cmCMakePath(file).GetParentPath();
1841 // Clear the implicit dependency makefile.
1842 auto depFile = cmCMakePath(dir).Append("compiler_depend.make");
1843 clearer.Clear(depFile.GenericString());
1845 // Remove the internal dependency check file
1846 auto internalDepFile =
1847 cmCMakePath(dir).Append("compiler_depend.internal");
1848 cmSystemTools::RemoveFile(internalDepFile.GenericString());
1850 // Touch timestamp file to force dependencies regeneration
1851 auto DepTimestamp = cmCMakePath(dir).Append("compiler_depend.ts");
1852 cmSystemTools::Touch(DepTimestamp.GenericString(), true);
1854 // clear the dependencies files generated by the compiler
1855 std::vector<std::string> dependencies = cmExpandedList(depsFiles, true);
1856 cmDependsCompiler depsManager;
1857 depsManager.SetVerbose(verbose);
1858 depsManager.ClearDependencies(dependencies);
1863 void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
1864 std::ostream& cmakefileStream, cmGeneratorTarget* target)
1866 // To enable dependencies filtering
1867 cmakefileStream << "\n"
1868 << "# Consider dependencies only in project.\n"
1869 << "set(CMAKE_DEPENDS_IN_PROJECT_ONLY "
1870 << (cmIsOn(this->Makefile->GetSafeDefinition(
1871 "CMAKE_DEPENDS_IN_PROJECT_ONLY"))
1876 auto const& implicitLangs =
1877 this->GetImplicitDepends(target, cmDependencyScannerKind::CMake);
1879 // list the languages
1880 cmakefileStream << "# The set of languages for which implicit "
1881 "dependencies are needed:\n";
1882 cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
1883 for (auto const& implicitLang : implicitLangs) {
1884 cmakefileStream << " \"" << implicitLang.first << "\"\n";
1886 cmakefileStream << " )\n";
1888 if (!implicitLangs.empty()) {
1889 // now list the files for each language
1891 << "# The set of files for implicit dependencies of each language:\n";
1892 for (auto const& implicitLang : implicitLangs) {
1893 const auto& lang = implicitLang.first;
1895 cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << lang << "\n";
1896 auto const& implicitPairs = implicitLang.second;
1898 // for each file pair
1899 for (auto const& implicitPair : implicitPairs) {
1900 for (auto const& di : implicitPair.second) {
1901 cmakefileStream << " \"" << di << "\" ";
1902 cmakefileStream << "\"" << implicitPair.first << "\"\n";
1905 cmakefileStream << " )\n";
1907 // Tell the dependency scanner what compiler is used.
1908 std::string cidVar = cmStrCat("CMAKE_", lang, "_COMPILER_ID");
1909 cmValue cid = this->Makefile->GetDefinition(cidVar);
1910 if (cmNonempty(cid)) {
1911 cmakefileStream << "set(CMAKE_" << lang << "_COMPILER_ID \"" << *cid
1915 if (lang == "Fortran") {
1916 std::string smodSep =
1917 this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
1918 std::string smodExt =
1919 this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
1920 cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_SEP \"" << smodSep
1922 cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_EXT \"" << smodExt
1926 // Build a list of preprocessor definitions for the target.
1927 std::set<std::string> defines;
1928 this->GetTargetDefines(target, this->GetConfigName(), lang, defines);
1929 if (!defines.empty()) {
1930 /* clang-format off */
1933 << "# Preprocessor definitions for this target.\n"
1934 << "set(CMAKE_TARGET_DEFINITIONS_" << lang << "\n";
1935 /* clang-format on */
1936 for (std::string const& define : defines) {
1937 cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define)
1940 cmakefileStream << " )\n";
1943 // Target-specific include directories:
1944 cmakefileStream << "\n"
1945 << "# The include file search paths:\n";
1946 cmakefileStream << "set(CMAKE_" << lang << "_TARGET_INCLUDE_PATH\n";
1947 std::vector<std::string> includes;
1949 this->GetIncludeDirectories(includes, target, lang,
1950 this->GetConfigName());
1951 std::string const& binaryDir = this->GetState()->GetBinaryDirectory();
1952 if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
1953 std::string const& sourceDir = this->GetState()->GetSourceDirectory();
1954 cm::erase_if(includes, ::NotInProjectDir(sourceDir, binaryDir));
1956 for (std::string const& include : includes) {
1957 cmakefileStream << " \"" << this->MaybeRelativeToTopBinDir(include)
1960 cmakefileStream << " )\n";
1963 // Store include transform rule properties. Write the directory
1964 // rules first because they may be overridden by later target rules.
1965 std::vector<std::string> transformRules;
1967 this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
1968 cmExpandList(*xform, transformRules);
1971 target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
1972 cmExpandList(*xform, transformRules);
1974 if (!transformRules.empty()) {
1975 cmakefileStream << "\nset(CMAKE_INCLUDE_TRANSFORMS\n";
1976 for (std::string const& tr : transformRules) {
1977 cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr)
1980 cmakefileStream << " )\n";
1984 auto const& compilerLangs =
1985 this->GetImplicitDepends(target, cmDependencyScannerKind::Compiler);
1987 // list the dependency files managed by the compiler
1988 cmakefileStream << "\n# The set of dependency files which are needed:\n";
1989 cmakefileStream << "set(CMAKE_DEPENDS_DEPENDENCY_FILES\n";
1990 for (auto const& compilerLang : compilerLangs) {
1991 auto const& compilerPairs = compilerLang.second;
1992 if (compilerLang.first == "CUSTOM"_s) {
1993 for (auto const& compilerPair : compilerPairs) {
1994 for (auto const& src : compilerPair.second) {
1995 cmakefileStream << R"( "" ")"
1996 << this->MaybeRelativeToTopBinDir(compilerPair.first)
1997 << R"(" "custom" ")"
1998 << this->MaybeRelativeToTopBinDir(src) << "\"\n";
2002 auto depFormat = this->Makefile->GetSafeDefinition(
2003 cmStrCat("CMAKE_", compilerLang.first, "_DEPFILE_FORMAT"));
2004 for (auto const& compilerPair : compilerPairs) {
2005 for (auto const& src : compilerPair.second) {
2006 cmakefileStream << " \"" << src << "\" \""
2007 << this->MaybeRelativeToTopBinDir(compilerPair.first)
2008 << "\" \"" << depFormat << "\" \""
2009 << this->MaybeRelativeToTopBinDir(compilerPair.first)
2015 cmakefileStream << " )\n";
2018 void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
2020 os << "# CMAKE generated file: DO NOT EDIT!\n"
2021 << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
2022 << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
2023 << cmVersion::GetMinorVersion() << "\n\n";
2026 std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
2027 const std::string& makefile, const std::string& tgt)
2029 // Call make on the given file.
2030 std::string cmd = cmStrCat(
2031 "$(MAKE) $(MAKESILENT) -f ",
2032 this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL), ' ');
2034 cmGlobalUnixMakefileGenerator3* gg =
2035 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
2036 // Pass down verbosity level.
2037 if (!gg->MakeSilentFlag.empty()) {
2038 cmd += gg->MakeSilentFlag;
2042 // Most unix makes will pass the command line flags to make down to
2043 // sub-invoked makes via an environment variable. However, some
2044 // makes do not support that, so you have to pass the flags
2046 if (gg->PassMakeflags) {
2047 cmd += "-$(MAKEFLAGS) ";
2052 // The make target is always relative to the top of the build tree.
2053 std::string tgt2 = this->MaybeRelativeToTopBinDir(tgt);
2055 // The target may have been written with windows paths.
2056 cmSystemTools::ConvertToOutputSlashes(tgt2);
2058 // Escape one extra time if the make tool requires it.
2059 if (this->MakeCommandEscapeTargetTwice) {
2060 tgt2 = this->EscapeForShell(tgt2, true, false);
2063 // The target name is now a string that should be passed verbatim
2064 // on the command line.
2065 cmd += this->EscapeForShell(tgt2, true, false);
2070 void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
2072 os << "#======================================"
2073 "=======================================\n";
2076 void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
2077 const std::string& s)
2079 // Write the given string to the stream with escaping to get it back
2080 // into CMake through the lexical scanner.
2085 } else if (c == '"') {
2094 std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
2095 const std::string& p, bool useWatcomQuote)
2097 // Split the path into its components.
2098 std::vector<std::string> components;
2099 cmSystemTools::SplitPath(p, components);
2101 // Open the quoted result.
2103 if (useWatcomQuote) {
2104 #if defined(_WIN32) && !defined(__CYGWIN__)
2113 // Return an empty path if there are no components.
2114 if (!components.empty()) {
2115 // Choose a slash direction and fix root component.
2116 const char* slash = "/";
2117 #if defined(_WIN32) && !defined(__CYGWIN__)
2118 if (!cmSystemTools::GetForceUnixPaths()) {
2120 for (char& i : components[0]) {
2128 // Begin the quoted result with the root component.
2129 result += components[0];
2131 if (components.size() > 1) {
2132 // Now add the rest of the components separated by the proper slash
2133 // direction for this platform.
2134 auto compEnd = std::remove(components.begin() + 1, components.end() - 1,
2136 auto compStart = components.begin() + 1;
2137 result += cmJoin(cmMakeRange(compStart, compEnd), slash);
2138 // Only the last component can be empty to avoid double slashes.
2140 result += components.back();
2144 // Close the quoted result.
2145 if (useWatcomQuote) {
2146 #if defined(_WIN32) && !defined(__CYGWIN__)
2158 std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
2159 cmGeneratorTarget const* target) const
2161 std::string dir = cmStrCat("CMakeFiles/", target->GetName());
2170 cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
2171 cmLocalUnixMakefileGenerator3::GetImplicitDepends(
2172 const cmGeneratorTarget* tgt, cmDependencyScannerKind scanner)
2174 return this->ImplicitDepends[tgt->GetName()][scanner];
2177 void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
2178 const cmGeneratorTarget* tgt, const std::string& lang,
2179 const std::string& obj, const std::string& src,
2180 cmDependencyScannerKind scanner)
2182 this->ImplicitDepends[tgt->GetName()][scanner][lang][obj].push_back(src);
2185 void cmLocalUnixMakefileGenerator3::CreateCDCommand(
2186 std::vector<std::string>& commands, std::string const& tgtDir,
2187 std::string const& relDir)
2189 // do we need to cd?
2190 if (tgtDir == relDir) {
2194 // In a Windows shell we must change drive letter too. The shell
2195 // used by NMake and Borland make does not support "cd /d" so this
2196 // feature simply cannot work with them (Borland make does not even
2197 // support changing the drive letter with just "d:").
2198 const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
2200 cmGlobalUnixMakefileGenerator3* gg =
2201 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
2203 // On Windows we must perform each step separately and then change
2204 // back because the shell keeps the working directory between
2207 cmStrCat(cd_cmd, this->ConvertToOutputForExisting(tgtDir));
2208 commands.insert(commands.begin(), cmd);
2210 // Change back to the starting directory.
2211 cmd = cmStrCat(cd_cmd, this->ConvertToOutputForExisting(relDir));
2212 commands.push_back(std::move(cmd));
2214 // On UNIX we must construct a single shell command to change
2215 // directory and build because make resets the directory between
2217 std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
2218 std::string prefix = cd_cmd + outputForExisting + " && ";
2219 std::transform(commands.begin(), commands.end(), commands.begin(),
2220 [&prefix](std::string const& s) { return prefix + s; });