STYLE: Fix typo in GetFilenameLastExtension docs
[cmake.git] / Source / cmLocalUnixMakefileGenerator3.cxx
bloba4279d064ef41e57535d649f47464dd51091e198
1 /*=========================================================================
3 Program: CMake - Cross-Platform Makefile Generator
4 Module: $RCSfile: cmLocalUnixMakefileGenerator3.cxx,v $
5 Language: C++
6 Date: $Date: 2008-10-09 19:30:07 $
7 Version: $Revision: 1.255 $
9 Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
10 See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.
12 This software is distributed WITHOUT ANY WARRANTY; without even
13 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 PURPOSE. See the above copyright notices for more information.
16 =========================================================================*/
17 #include "cmLocalUnixMakefileGenerator3.h"
19 #include "cmDepends.h"
20 #include "cmGeneratedFileStream.h"
21 #include "cmGlobalUnixMakefileGenerator3.h"
22 #include "cmMakefile.h"
23 #include "cmMakefileTargetGenerator.h"
24 #include "cmSourceFile.h"
25 #include "cmake.h"
26 #include "cmVersion.h"
27 #include "cmFileTimeComparison.h"
29 // Include dependency scanners for supported languages. Only the
30 // C/C++ scanner is needed for bootstrapping CMake.
31 #include "cmDependsC.h"
32 #ifdef CMAKE_BUILD_WITH_CMAKE
33 # include "cmDependsFortran.h"
34 # include "cmDependsJava.h"
35 # include <cmsys/Terminal.h>
36 #endif
38 #include <memory> // auto_ptr
39 #include <queue>
41 //----------------------------------------------------------------------------
42 // Helper function used below.
43 static std::string cmSplitExtension(std::string const& in, std::string& base)
45 std::string ext;
46 std::string::size_type dot_pos = in.rfind(".");
47 if(dot_pos != std::string::npos)
49 // Remove the extension first in case &base == &in.
50 ext = in.substr(dot_pos, std::string::npos);
51 base = in.substr(0, dot_pos);
53 else
55 base = in;
57 return ext;
60 //----------------------------------------------------------------------------
61 cmLocalUnixMakefileGenerator3::cmLocalUnixMakefileGenerator3()
63 this->SilentNoColon = false;
64 this->WindowsShell = false;
65 this->IncludeDirective = "include";
66 this->MakefileVariableSize = 0;
67 this->IgnoreLibPrefix = false;
68 this->PassMakeflags = false;
69 this->DefineWindowsNULL = false;
70 this->UnixCD = true;
71 this->ColorMakefile = false;
72 this->SkipPreprocessedSourceRules = false;
73 this->SkipAssemblySourceRules = false;
74 this->NativeEchoCommand = "@echo ";
75 this->NativeEchoWindows = true;
76 this->MakeCommandEscapeTargetTwice = false;
77 this->IsMakefileGenerator = true;
78 this->BorlandMakeCurlyHack = false;
81 //----------------------------------------------------------------------------
82 cmLocalUnixMakefileGenerator3::~cmLocalUnixMakefileGenerator3()
86 //----------------------------------------------------------------------------
87 void cmLocalUnixMakefileGenerator3::Configure()
89 // Compute the path to use when referencing the current output
90 // directory from the top output directory.
91 this->HomeRelativeOutputPath =
92 this->Convert(this->Makefile->GetStartOutputDirectory(), HOME_OUTPUT);
93 if(this->HomeRelativeOutputPath == ".")
95 this->HomeRelativeOutputPath = "";
97 if(!this->HomeRelativeOutputPath.empty())
99 this->HomeRelativeOutputPath += "/";
101 this->cmLocalGenerator::Configure();
104 //----------------------------------------------------------------------------
105 void cmLocalUnixMakefileGenerator3::Generate()
107 // Store the configuration name that will be generated.
108 if(const char* config = this->Makefile->GetDefinition("CMAKE_BUILD_TYPE"))
110 // Use the build type given by the user.
111 this->ConfigurationName = config;
113 else
115 // No configuration type given.
116 this->ConfigurationName = "";
119 // Record whether some options are enabled to avoid checking many
120 // times later.
121 this->ColorMakefile = this->Makefile->IsOn("CMAKE_COLOR_MAKEFILE");
122 this->SkipPreprocessedSourceRules =
123 this->Makefile->IsOn("CMAKE_SKIP_PREPROCESSED_SOURCE_RULES");
124 this->SkipAssemblySourceRules =
125 this->Makefile->IsOn("CMAKE_SKIP_ASSEMBLY_SOURCE_RULES");
127 // Generate the rule files for each target.
128 cmTargets& targets = this->Makefile->GetTargets();
129 std::string empty;
130 for(cmTargets::iterator t = targets.begin(); t != targets.end(); ++t)
132 cmMakefileTargetGenerator *tg =
133 cmMakefileTargetGenerator::New(&(t->second));
134 if (tg)
136 this->TargetGenerators.push_back(tg);
137 tg->WriteRuleFiles();
141 // write the local Makefile
142 this->WriteLocalMakefile();
144 // Write the cmake file with information for this directory.
145 this->WriteDirectoryInformationFile();
148 //----------------------------------------------------------------------------
149 // return info about progress actions
150 unsigned long cmLocalUnixMakefileGenerator3::GetNumberOfProgressActions()
152 unsigned long result = 0;
154 for (std::vector<cmMakefileTargetGenerator *>::iterator mtgIter =
155 this->TargetGenerators.begin();
156 mtgIter != this->TargetGenerators.end(); ++mtgIter)
158 result += (*mtgIter)->GetNumberOfProgressActions();
160 return result;
163 //----------------------------------------------------------------------------
164 // return info about progress actions
165 unsigned long cmLocalUnixMakefileGenerator3
166 ::GetNumberOfProgressActionsForTarget(const char *name)
168 for (std::vector<cmMakefileTargetGenerator *>::iterator mtgIter =
169 this->TargetGenerators.begin();
170 mtgIter != this->TargetGenerators.end(); ++mtgIter)
172 if (!strcmp(name,(*mtgIter)->GetTarget()->GetName()))
174 return (*mtgIter)->GetNumberOfProgressActions();
177 return 0;
181 //----------------------------------------------------------------------------
182 // writes the progreess variables and also closes out the targets
183 void cmLocalUnixMakefileGenerator3
184 ::WriteProgressVariables(unsigned long total,
185 unsigned long &current)
187 // delete the makefile target generator objects
188 for (std::vector<cmMakefileTargetGenerator *>::iterator mtgIter =
189 this->TargetGenerators.begin();
190 mtgIter != this->TargetGenerators.end(); ++mtgIter)
192 (*mtgIter)->WriteProgressVariables(total,current);
193 delete *mtgIter;
195 this->TargetGenerators.clear();
198 void cmLocalUnixMakefileGenerator3::WriteAllProgressVariable()
200 // write the top level progress for the all target
201 std::string progressFile = cmake::GetCMakeFilesDirectory();
202 progressFile += "/progress.make";
203 std::string progressFileNameFull =
204 this->ConvertToFullPath(progressFile.c_str());
205 cmGeneratedFileStream ruleFileStream(progressFileNameFull.c_str());
206 if(!ruleFileStream)
208 return;
211 cmGlobalUnixMakefileGenerator3 *gg =
212 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
214 ruleFileStream << gg->GetNumberOfProgressActionsInAll(this) << "\n";
217 //----------------------------------------------------------------------------
218 void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
220 // generate the includes
221 std::string ruleFileName = "Makefile";
223 // Open the rule file. This should be copy-if-different because the
224 // rules may depend on this file itself.
225 std::string ruleFileNameFull = this->ConvertToFullPath(ruleFileName);
226 cmGeneratedFileStream ruleFileStream(ruleFileNameFull.c_str());
227 if(!ruleFileStream)
229 return;
231 // always write the top makefile
232 if (this->Parent)
234 ruleFileStream.SetCopyIfDifferent(true);
237 // write the all rules
238 this->WriteLocalAllRules(ruleFileStream);
240 // only write local targets unless at the top Keep track of targets already
241 // listed.
242 std::set<cmStdString> emittedTargets;
243 if (this->Parent)
245 // write our targets, and while doing it collect up the object
246 // file rules
247 this->WriteLocalMakefileTargets(ruleFileStream,emittedTargets);
249 else
251 cmGlobalUnixMakefileGenerator3 *gg =
252 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
253 gg->WriteConvenienceRules(ruleFileStream,emittedTargets);
256 bool do_preprocess_rules =
257 this->GetCreatePreprocessedSourceRules();
258 bool do_assembly_rules =
259 this->GetCreateAssemblySourceRules();
261 // now write out the object rules
262 // for each object file name
263 for (std::map<cmStdString, LocalObjectInfo>::iterator lo =
264 this->LocalObjectFiles.begin();
265 lo != this->LocalObjectFiles.end(); ++lo)
267 // Add a convenience rule for building the object file.
268 this->WriteObjectConvenienceRule(ruleFileStream,
269 "target to build an object file",
270 lo->first.c_str(), lo->second);
272 // Check whether preprocessing and assembly rules make sense.
273 // They make sense only for C and C++ sources.
274 bool lang_is_c_or_cxx = false;
275 for(std::vector<LocalObjectEntry>::const_iterator ei =
276 lo->second.begin(); ei != lo->second.end(); ++ei)
278 if(ei->Language == "C" || ei->Language == "CXX")
280 lang_is_c_or_cxx = true;
284 // Add convenience rules for preprocessed and assembly files.
285 if(lang_is_c_or_cxx && (do_preprocess_rules || do_assembly_rules))
287 std::string::size_type dot_pos = lo->first.rfind(".");
288 std::string base = lo->first.substr(0, dot_pos);
289 if(do_preprocess_rules)
291 this->WriteObjectConvenienceRule(
292 ruleFileStream, "target to preprocess a source file",
293 (base + ".i").c_str(), lo->second);
295 if(do_assembly_rules)
297 this->WriteObjectConvenienceRule(
298 ruleFileStream, "target to generate assembly for a file",
299 (base + ".s").c_str(), lo->second);
304 // add a help target as long as there isn;t a real target named help
305 if(emittedTargets.insert("help").second)
307 cmGlobalUnixMakefileGenerator3 *gg =
308 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
309 gg->WriteHelpRule(ruleFileStream,this);
312 this->WriteSpecialTargetsBottom(ruleFileStream);
315 //----------------------------------------------------------------------------
316 void
317 cmLocalUnixMakefileGenerator3
318 ::WriteObjectConvenienceRule(std::ostream& ruleFileStream,
319 const char* comment, const char* output,
320 LocalObjectInfo const& info)
322 // If the rule includes the source file extension then create a
323 // version that has the extension removed. The help should include
324 // only the version without source extension.
325 bool inHelp = true;
326 if(info.HasSourceExtension)
328 // Remove the last extension. This should be kept.
329 std::string outBase1 = output;
330 std::string outExt1 = cmSplitExtension(outBase1, outBase1);
332 // Now remove the source extension and put back the last
333 // extension.
334 std::string outNoExt;
335 cmSplitExtension(outBase1, outNoExt);
336 outNoExt += outExt1;
338 // Add a rule to drive the rule below.
339 std::vector<std::string> depends;
340 depends.push_back(output);
341 std::vector<std::string> no_commands;
342 this->WriteMakeRule(ruleFileStream, 0,
343 outNoExt.c_str(), depends, no_commands, true, true);
344 inHelp = false;
347 // Recursively make the rule for each target using the object file.
348 std::vector<std::string> commands;
349 for(std::vector<LocalObjectEntry>::const_iterator t = info.begin();
350 t != info.end(); ++t)
352 std::string tgtMakefileName =
353 this->GetRelativeTargetDirectory(*(t->Target));
354 std::string targetName = tgtMakefileName;
355 tgtMakefileName += "/build.make";
356 targetName += "/";
357 targetName += output;
358 commands.push_back(
359 this->GetRecursiveMakeCall(tgtMakefileName.c_str(), targetName.c_str())
362 this->CreateCDCommand(commands,
363 this->Makefile->GetHomeOutputDirectory(),
364 cmLocalGenerator::START_OUTPUT);
366 // Write the rule to the makefile.
367 std::vector<std::string> no_depends;
368 this->WriteMakeRule(ruleFileStream, comment,
369 output, no_depends, commands, true, inHelp);
372 //----------------------------------------------------------------------------
373 void cmLocalUnixMakefileGenerator3
374 ::WriteLocalMakefileTargets(std::ostream& ruleFileStream,
375 std::set<cmStdString> &emitted)
377 std::vector<std::string> depends;
378 std::vector<std::string> commands;
380 // for each target we just provide a rule to cd up to the top and do a make
381 // on the target
382 cmTargets& targets = this->Makefile->GetTargets();
383 std::string localName;
384 for(cmTargets::iterator t = targets.begin(); t != targets.end(); ++t)
386 if((t->second.GetType() == cmTarget::EXECUTABLE) ||
387 (t->second.GetType() == cmTarget::STATIC_LIBRARY) ||
388 (t->second.GetType() == cmTarget::SHARED_LIBRARY) ||
389 (t->second.GetType() == cmTarget::MODULE_LIBRARY) ||
390 (t->second.GetType() == cmTarget::UTILITY))
392 emitted.insert(t->second.GetName());
394 // for subdirs add a rule to build this specific target by name.
395 localName = this->GetRelativeTargetDirectory(t->second);
396 localName += "/rule";
397 commands.clear();
398 depends.clear();
400 // Build the target for this pass.
401 std::string makefile2 = cmake::GetCMakeFilesDirectoryPostSlash();
402 makefile2 += "Makefile2";
403 commands.push_back(this->GetRecursiveMakeCall
404 (makefile2.c_str(),localName.c_str()));
405 this->CreateCDCommand(commands,
406 this->Makefile->GetHomeOutputDirectory(),
407 cmLocalGenerator::START_OUTPUT);
408 this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
409 localName.c_str(), depends, commands, true);
411 // Add a target with the canonical name (no prefix, suffix or path).
412 if(localName != t->second.GetName())
414 commands.clear();
415 depends.push_back(localName);
416 this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
417 t->second.GetName(), depends, commands, true);
420 // Add a fast rule to build the target
421 std::string makefileName = this->GetRelativeTargetDirectory(t->second);
422 makefileName += "/build.make";
423 // make sure the makefile name is suitable for a makefile
424 std::string makeTargetName =
425 this->GetRelativeTargetDirectory(t->second);
426 makeTargetName += "/build";
427 localName = t->second.GetName();
428 localName += "/fast";
429 depends.clear();
430 commands.clear();
431 commands.push_back(this->GetRecursiveMakeCall
432 (makefileName.c_str(), makeTargetName.c_str()));
433 this->CreateCDCommand(commands,
434 this->Makefile->GetHomeOutputDirectory(),
435 cmLocalGenerator::START_OUTPUT);
436 this->WriteMakeRule(ruleFileStream, "fast build rule for target.",
437 localName.c_str(), depends, commands, true);
439 // Add a local name for the rule to relink the target before
440 // installation.
441 if(t->second.NeedRelinkBeforeInstall())
443 makeTargetName = this->GetRelativeTargetDirectory(t->second);
444 makeTargetName += "/preinstall";
445 localName = t->second.GetName();
446 localName += "/preinstall";
447 depends.clear();
448 commands.clear();
449 commands.push_back(this->GetRecursiveMakeCall
450 (makefile2.c_str(), makeTargetName.c_str()));
451 this->CreateCDCommand(commands,
452 this->Makefile->GetHomeOutputDirectory(),
453 cmLocalGenerator::START_OUTPUT);
454 this->WriteMakeRule(ruleFileStream,
455 "Manual pre-install relink rule for target.",
456 localName.c_str(), depends, commands, true);
462 //----------------------------------------------------------------------------
463 void cmLocalUnixMakefileGenerator3::WriteDirectoryInformationFile()
465 std::string infoFileName = this->Makefile->GetStartOutputDirectory();
466 infoFileName += cmake::GetCMakeFilesDirectory();
467 infoFileName += "/CMakeDirectoryInformation.cmake";
469 // Open the output file.
470 cmGeneratedFileStream infoFileStream(infoFileName.c_str());
471 if(!infoFileStream)
473 return;
476 // Write the do not edit header.
477 this->WriteDisclaimer(infoFileStream);
479 // Setup relative path conversion tops.
480 infoFileStream
481 << "# Relative path conversion top directories.\n"
482 << "SET(CMAKE_RELATIVE_PATH_TOP_SOURCE \"" << this->RelativePathTopSource
483 << "\")\n"
484 << "SET(CMAKE_RELATIVE_PATH_TOP_BINARY \"" << this->RelativePathTopBinary
485 << "\")\n"
486 << "\n";
488 // Tell the dependency scanner to use unix paths if necessary.
489 if(cmSystemTools::GetForceUnixPaths())
491 infoFileStream
492 << "# Force unix paths in dependencies.\n"
493 << "SET(CMAKE_FORCE_UNIX_PATHS 1)\n"
494 << "\n";
497 // Store the include search path for this directory.
498 infoFileStream
499 << "# The C and CXX include file search paths:\n";
500 infoFileStream
501 << "SET(CMAKE_C_INCLUDE_PATH\n";
502 std::vector<std::string> includeDirs;
503 this->GetIncludeDirectories(includeDirs, false);
504 for(std::vector<std::string>::iterator i = includeDirs.begin();
505 i != includeDirs.end(); ++i)
507 infoFileStream
508 << " \"" << this->Convert(i->c_str(),HOME_OUTPUT).c_str() << "\"\n";
510 infoFileStream
511 << " )\n";
512 infoFileStream
513 << "SET(CMAKE_CXX_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH})\n";
514 infoFileStream
515 << "SET(CMAKE_Fortran_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH})\n";
517 // Store the include regular expressions for this directory.
518 infoFileStream
519 << "\n"
520 << "# The C and CXX include file regular expressions for "
521 << "this directory.\n";
522 infoFileStream
523 << "SET(CMAKE_C_INCLUDE_REGEX_SCAN ";
524 this->WriteCMakeArgument(infoFileStream,
525 this->Makefile->GetIncludeRegularExpression());
526 infoFileStream
527 << ")\n";
528 infoFileStream
529 << "SET(CMAKE_C_INCLUDE_REGEX_COMPLAIN ";
530 this->WriteCMakeArgument(infoFileStream,
531 this->Makefile->GetComplainRegularExpression());
532 infoFileStream
533 << ")\n";
534 infoFileStream
535 << "SET(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})\n";
536 infoFileStream
537 << "SET(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN "
538 "${CMAKE_C_INCLUDE_REGEX_COMPLAIN})\n";
541 //----------------------------------------------------------------------------
542 std::string
543 cmLocalUnixMakefileGenerator3
544 ::ConvertToFullPath(const std::string& localPath)
546 std::string dir = this->Makefile->GetStartOutputDirectory();
547 dir += "/";
548 dir += localPath;
549 return dir;
553 const std::string &cmLocalUnixMakefileGenerator3::GetHomeRelativeOutputPath()
555 return this->HomeRelativeOutputPath;
559 //----------------------------------------------------------------------------
560 void
561 cmLocalUnixMakefileGenerator3
562 ::WriteMakeRule(std::ostream& os,
563 const char* comment,
564 const char* target,
565 const std::vector<std::string>& depends,
566 const std::vector<std::string>& commands,
567 bool symbolic,
568 bool in_help)
570 // Make sure there is a target.
571 if(!target || !*target)
573 cmSystemTools::Error("No target for WriteMakeRule! called with comment: ",
574 comment);
575 return;
578 std::string replace;
580 // Write the comment describing the rule in the makefile.
581 if(comment)
583 replace = comment;
584 std::string::size_type lpos = 0;
585 std::string::size_type rpos;
586 while((rpos = replace.find('\n', lpos)) != std::string::npos)
588 os << "# " << replace.substr(lpos, rpos-lpos) << "\n";
589 lpos = rpos+1;
591 os << "# " << replace.substr(lpos) << "\n";
594 // Construct the left hand side of the rule.
595 replace = target;
596 std::string tgt = this->Convert(replace.c_str(),HOME_OUTPUT,MAKEFILE);
597 const char* space = "";
598 if(tgt.size() == 1)
600 // Add a space before the ":" to avoid drive letter confusion on
601 // Windows.
602 space = " ";
605 // Mark the rule as symbolic if requested.
606 if(symbolic)
608 if(const char* sym =
609 this->Makefile->GetDefinition("CMAKE_MAKE_SYMBOLIC_RULE"))
611 os << tgt.c_str() << space << ": " << sym << "\n";
615 // Write the rule.
616 if(depends.empty())
618 // No dependencies. The commands will always run.
619 os << tgt.c_str() << space << ":\n";
621 else
623 // Split dependencies into multiple rule lines. This allows for
624 // very long dependency lists even on older make implementations.
625 for(std::vector<std::string>::const_iterator dep = depends.begin();
626 dep != depends.end(); ++dep)
628 replace = *dep;
629 replace = this->Convert(replace.c_str(),HOME_OUTPUT,MAKEFILE);
630 os << tgt.c_str() << space << ": " << replace.c_str() << "\n";
634 // Write the list of commands.
635 for(std::vector<std::string>::const_iterator i = commands.begin();
636 i != commands.end(); ++i)
638 replace = *i;
639 os << "\t" << replace.c_str() << "\n";
641 if(symbolic && !this->WatcomWMake)
643 os << ".PHONY : " << tgt.c_str() << "\n";
645 os << "\n";
646 // Add the output to the local help if requested.
647 if(in_help)
649 this->LocalHelp.push_back(target);
653 //----------------------------------------------------------------------------
654 void
655 cmLocalUnixMakefileGenerator3
656 ::WriteMakeVariables(std::ostream& makefileStream)
658 this->WriteDivider(makefileStream);
659 makefileStream
660 << "# Set environment variables for the build.\n"
661 << "\n";
662 if(this->DefineWindowsNULL)
664 makefileStream
665 << "!IF \"$(OS)\" == \"Windows_NT\"\n"
666 << "NULL=\n"
667 << "!ELSE\n"
668 << "NULL=nul\n"
669 << "!ENDIF\n";
671 if(this->WindowsShell)
673 makefileStream
674 << "SHELL = cmd.exe\n"
675 << "\n";
677 else
679 makefileStream
680 << "# The shell in which to execute make rules.\n"
681 << "SHELL = /bin/sh\n"
682 << "\n";
685 std::string cmakecommand =
686 this->Makefile->GetRequiredDefinition("CMAKE_COMMAND");
687 makefileStream
688 << "# The CMake executable.\n"
689 << "CMAKE_COMMAND = "
690 << this->Convert(cmakecommand.c_str(), FULL, SHELL).c_str()
691 << "\n"
692 << "\n";
693 makefileStream
694 << "# The command to remove a file.\n"
695 << "RM = "
696 << this->Convert(cmakecommand.c_str(),FULL,SHELL).c_str()
697 << " -E remove -f\n"
698 << "\n";
700 if(const char* edit_cmd =
701 this->Makefile->GetDefinition("CMAKE_EDIT_COMMAND"))
703 makefileStream
704 << "# The program to use to edit the cache.\n"
705 << "CMAKE_EDIT_COMMAND = "
706 << this->Convert(edit_cmd,FULL,SHELL) << "\n"
707 << "\n";
710 makefileStream
711 << "# The top-level source directory on which CMake was run.\n"
712 << "CMAKE_SOURCE_DIR = "
713 << this->Convert(this->Makefile->GetHomeDirectory(), FULL, SHELL)
714 << "\n"
715 << "\n";
716 makefileStream
717 << "# The top-level build directory on which CMake was run.\n"
718 << "CMAKE_BINARY_DIR = "
719 << this->Convert(this->Makefile->GetHomeOutputDirectory(), FULL, SHELL)
720 << "\n"
721 << "\n";
724 //----------------------------------------------------------------------------
725 void
726 cmLocalUnixMakefileGenerator3
727 ::WriteSpecialTargetsTop(std::ostream& makefileStream)
729 this->WriteDivider(makefileStream);
730 makefileStream
731 << "# Special targets provided by cmake.\n"
732 << "\n";
734 std::vector<std::string> no_commands;
735 std::vector<std::string> no_depends;
737 // Special target to cleanup operation of make tool.
738 // This should be the first target except for the default_target in
739 // the interface Makefile.
740 this->WriteMakeRule(
741 makefileStream, "Disable implicit rules so canoncical targets will work.",
742 ".SUFFIXES", no_depends, no_commands, false);
744 if(!this->NMake && !this->WatcomWMake && !this->BorlandMakeCurlyHack)
746 // turn off RCS and SCCS automatic stuff from gmake
747 makefileStream
748 << "# Remove some rules from gmake that .SUFFIXES does not remove.\n"
749 << "SUFFIXES =\n\n";
751 // Add a fake suffix to keep HP happy. Must be max 32 chars for SGI make.
752 std::vector<std::string> depends;
753 depends.push_back(".hpux_make_needs_suffix_list");
754 this->WriteMakeRule(makefileStream, 0,
755 ".SUFFIXES", depends, no_commands, false);
757 cmGlobalUnixMakefileGenerator3* gg =
758 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
759 // Write special target to silence make output. This must be after
760 // the default target in case VERBOSE is set (which changes the
761 // name). The setting of CMAKE_VERBOSE_MAKEFILE to ON will cause a
762 // "VERBOSE=1" to be added as a make variable which will change the
763 // name of this special target. This gives a make-time choice to
764 // the user.
765 if((this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE"))
766 || (gg->GetForceVerboseMakefiles()))
768 makefileStream
769 << "# Produce verbose output by default.\n"
770 << "VERBOSE = 1\n"
771 << "\n";
773 if(this->SilentNoColon)
775 makefileStream << "$(VERBOSE).SILENT\n";
777 else
779 this->WriteMakeRule(makefileStream,
780 "Suppress display of executed commands.",
781 "$(VERBOSE).SILENT",
782 no_depends,
783 no_commands, false);
786 // Work-around for makes that drop rules that have no dependencies
787 // or commands.
788 std::string hack = gg->GetEmptyRuleHackDepends();
789 if(!hack.empty())
791 no_depends.push_back(hack);
793 std::string hack_cmd = gg->GetEmptyRuleHackCommand();
794 if(!hack_cmd.empty())
796 no_commands.push_back(hack_cmd);
799 // Special symbolic target that never exists to force dependers to
800 // run their rules.
801 this->WriteMakeRule
802 (makefileStream,
803 "A target that is always out of date.",
804 "cmake_force", no_depends, no_commands, true);
806 // Variables for reference by other rules.
807 this->WriteMakeVariables(makefileStream);
810 //----------------------------------------------------------------------------
811 void cmLocalUnixMakefileGenerator3
812 ::WriteSpecialTargetsBottom(std::ostream& makefileStream)
814 this->WriteDivider(makefileStream);
815 makefileStream
816 << "# Special targets to cleanup operation of make.\n"
817 << "\n";
819 // Write special "cmake_check_build_system" target to run cmake with
820 // the --check-build-system flag.
822 // Build command to run CMake to check if anything needs regenerating.
823 std::string cmakefileName = cmake::GetCMakeFilesDirectoryPostSlash();
824 cmakefileName += "Makefile.cmake";
825 std::string runRule =
826 "$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
827 runRule += " --check-build-system ";
828 runRule += this->Convert(cmakefileName.c_str(),NONE,SHELL);
829 runRule += " 0";
831 std::vector<std::string> no_depends;
832 std::vector<std::string> commands;
833 commands.push_back(runRule);
834 if(this->Parent)
836 this->CreateCDCommand(commands,
837 this->Makefile->GetHomeOutputDirectory(),
838 cmLocalGenerator::START_OUTPUT);
840 this->WriteMakeRule(makefileStream,
841 "Special rule to run CMake to check the build system "
842 "integrity.\n"
843 "No rule that depends on this can have "
844 "commands that come from listfiles\n"
845 "because they might be regenerated.",
846 "cmake_check_build_system",
847 no_depends,
848 commands, true);
854 //----------------------------------------------------------------------------
855 void
856 cmLocalUnixMakefileGenerator3
857 ::WriteConvenienceRule(std::ostream& ruleFileStream,
858 const char* realTarget,
859 const char* helpTarget)
861 // A rule is only needed if the names are different.
862 if(strcmp(realTarget, helpTarget) != 0)
864 // The helper target depends on the real target.
865 std::vector<std::string> depends;
866 depends.push_back(realTarget);
868 // There are no commands.
869 std::vector<std::string> no_commands;
871 // Write the rule.
872 this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
873 helpTarget, depends, no_commands, true);
878 //----------------------------------------------------------------------------
879 std::string
880 cmLocalUnixMakefileGenerator3
881 ::GetRelativeTargetDirectory(cmTarget const& target)
883 std::string dir = this->HomeRelativeOutputPath;
884 dir += this->GetTargetDirectory(target);
885 return this->Convert(dir.c_str(),NONE,UNCHANGED);
890 //----------------------------------------------------------------------------
891 void cmLocalUnixMakefileGenerator3::AppendFlags(std::string& flags,
892 const char* newFlags)
894 if(this->WatcomWMake && newFlags && *newFlags)
896 std::string newf = newFlags;
897 if(newf.find("\\\"") != newf.npos)
899 cmSystemTools::ReplaceString(newf, "\\\"", "\"");
900 this->cmLocalGenerator::AppendFlags(flags, newf.c_str());
901 return;
904 this->cmLocalGenerator::AppendFlags(flags, newFlags);
907 //----------------------------------------------------------------------------
908 void
909 cmLocalUnixMakefileGenerator3
910 ::AppendRuleDepend(std::vector<std::string>& depends,
911 const char* ruleFileName)
913 // Add a dependency on the rule file itself unless an option to skip
914 // it is specifically enabled by the user or project.
915 const char* nodep =
916 this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY");
917 if(!nodep || cmSystemTools::IsOff(nodep))
919 depends.push_back(ruleFileName);
923 //----------------------------------------------------------------------------
924 void
925 cmLocalUnixMakefileGenerator3
926 ::AppendCustomDepends(std::vector<std::string>& depends,
927 const std::vector<cmCustomCommand>& ccs)
929 for(std::vector<cmCustomCommand>::const_iterator i = ccs.begin();
930 i != ccs.end(); ++i)
932 this->AppendCustomDepend(depends, *i);
936 //----------------------------------------------------------------------------
937 void
938 cmLocalUnixMakefileGenerator3
939 ::AppendCustomDepend(std::vector<std::string>& depends,
940 const cmCustomCommand& cc)
942 for(std::vector<std::string>::const_iterator d = cc.GetDepends().begin();
943 d != cc.GetDepends().end(); ++d)
945 // Lookup the real name of the dependency in case it is a CMake target.
946 std::string dep = this->GetRealDependency
947 (d->c_str(), this->ConfigurationName.c_str());
948 depends.push_back(dep);
952 //----------------------------------------------------------------------------
953 void
954 cmLocalUnixMakefileGenerator3
955 ::AppendCustomCommands(std::vector<std::string>& commands,
956 const std::vector<cmCustomCommand>& ccs,
957 cmLocalGenerator::RelativeRoot relative)
959 for(std::vector<cmCustomCommand>::const_iterator i = ccs.begin();
960 i != ccs.end(); ++i)
962 this->AppendCustomCommand(commands, *i, true, relative);
966 //----------------------------------------------------------------------------
967 void
968 cmLocalUnixMakefileGenerator3
969 ::AppendCustomCommand(std::vector<std::string>& commands,
970 const cmCustomCommand& cc, bool echo_comment,
971 cmLocalGenerator::RelativeRoot relative)
973 // Optionally create a command to display the custom command's
974 // comment text. This is used for pre-build, pre-link, and
975 // post-build command comments. Custom build step commands have
976 // their comments generated elsewhere.
977 if(echo_comment)
979 const char* comment = cc.GetComment();
980 if(comment && *comment)
982 this->AppendEcho(commands, comment,
983 cmLocalUnixMakefileGenerator3::EchoGenerate);
987 // if the command specified a working directory use it.
988 const char* dir = this->Makefile->GetStartOutputDirectory();
989 const char* workingDir = cc.GetWorkingDirectory();
990 if(workingDir)
992 dir = workingDir;
994 bool escapeOldStyle = cc.GetEscapeOldStyle();
995 bool escapeAllowMakeVars = cc.GetEscapeAllowMakeVars();
997 // Add each command line to the set of commands.
998 std::vector<std::string> commands1;
999 for(cmCustomCommandLines::const_iterator cl = cc.GetCommandLines().begin();
1000 cl != cc.GetCommandLines().end(); ++cl)
1002 // Build the command line in a single string.
1003 const cmCustomCommandLine& commandLine = *cl;
1004 std::string cmd = GetRealLocation(commandLine[0].c_str(),
1005 this->ConfigurationName.c_str());
1006 if (cmd.size())
1008 cmSystemTools::ReplaceString(cmd, "/./", "/");
1009 // Convert the command to a relative path only if the current
1010 // working directory will be the start-output directory.
1011 bool had_slash = cmd.find("/") != cmd.npos;
1012 if(!workingDir)
1014 cmd = this->Convert(cmd.c_str(),START_OUTPUT);
1016 bool has_slash = cmd.find("/") != cmd.npos;
1017 if(had_slash && !has_slash)
1019 // This command was specified as a path to a file in the
1020 // current directory. Add a leading "./" so it can run
1021 // without the current directory being in the search path.
1022 cmd = "./" + cmd;
1024 if(this->WatcomWMake &&
1025 cmSystemTools::FileIsFullPath(cmd.c_str()) &&
1026 cmd.find(" ") != cmd.npos)
1028 // On Watcom WMake use the windows short path for the command
1029 // name. This is needed to avoid funny quoting problems on
1030 // lines with shell redirection operators.
1031 std::string scmd;
1032 if(cmSystemTools::GetShortPath(cmd.c_str(), scmd))
1034 cmd = scmd;
1037 cmd = this->Convert(cmd.c_str(),NONE,SHELL);
1038 for(unsigned int j=1; j < commandLine.size(); ++j)
1040 cmd += " ";
1041 if(escapeOldStyle)
1043 cmd += this->EscapeForShellOldStyle(commandLine[j].c_str());
1045 else
1047 cmd += this->EscapeForShell(commandLine[j].c_str(),
1048 escapeAllowMakeVars);
1051 if(this->BorlandMakeCurlyHack)
1053 // Borland Make has a very strange bug. If the first curly
1054 // brace anywhere in the command string is a left curly, it
1055 // must be written {{} instead of just {. Otherwise some
1056 // curly braces are removed. The hack can be skipped if the
1057 // first curly brace is the last character.
1058 std::string::size_type lcurly = cmd.find("{");
1059 if(lcurly != cmd.npos && lcurly < (cmd.size()-1))
1061 std::string::size_type rcurly = cmd.find("}");
1062 if(rcurly == cmd.npos || rcurly > lcurly)
1064 // The first curly is a left curly. Use the hack.
1065 std::string hack_cmd = cmd.substr(0, lcurly);
1066 hack_cmd += "{{}";
1067 hack_cmd += cmd.substr(lcurly+1);
1068 cmd = hack_cmd;
1072 commands1.push_back(cmd);
1076 // Setup the proper working directory for the commands.
1077 this->CreateCDCommand(commands1, dir, relative);
1079 // push back the custom commands
1080 commands.insert(commands.end(), commands1.begin(), commands1.end());
1083 //----------------------------------------------------------------------------
1084 void
1085 cmLocalUnixMakefileGenerator3
1086 ::AppendCleanCommand(std::vector<std::string>& commands,
1087 const std::vector<std::string>& files,
1088 cmTarget& target, const char* filename)
1090 if(!files.empty())
1092 std::string cleanfile = this->Makefile->GetCurrentOutputDirectory();
1093 cleanfile += "/";
1094 cleanfile += this->GetTargetDirectory(target);
1095 cleanfile += "/cmake_clean";
1096 if(filename)
1098 cleanfile += "_";
1099 cleanfile += filename;
1101 cleanfile += ".cmake";
1102 std::string cleanfilePath = this->Convert(cleanfile.c_str(), FULL);
1103 std::ofstream fout(cleanfilePath.c_str());
1104 if(!fout)
1106 cmSystemTools::Error("Could not create ", cleanfilePath.c_str());
1108 fout << "FILE(REMOVE_RECURSE\n";
1109 std::string remove = "$(CMAKE_COMMAND) -P ";
1110 remove += this->Convert(cleanfile.c_str(), START_OUTPUT, SHELL);
1111 for(std::vector<std::string>::const_iterator f = files.begin();
1112 f != files.end(); ++f)
1114 std::string fc = this->Convert(f->c_str(),START_OUTPUT,UNCHANGED);
1115 fout << " " << this->EscapeForCMake(fc.c_str()) << "\n";
1117 fout << ")\n";
1118 commands.push_back(remove);
1120 // For the main clean rule add per-language cleaning.
1121 if(!filename)
1123 // Get the set of source languages in the target.
1124 std::set<cmStdString> languages;
1125 target.GetLanguages(languages);
1126 fout << "\n"
1127 << "# Per-language clean rules from dependency scanning.\n"
1128 << "FOREACH(lang";
1129 for(std::set<cmStdString>::const_iterator l = languages.begin();
1130 l != languages.end(); ++l)
1132 fout << " " << *l;
1134 fout << ")\n"
1135 << " INCLUDE(" << this->GetTargetDirectory(target)
1136 << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
1137 << "ENDFOREACH(lang)\n";
1142 //----------------------------------------------------------------------------
1143 void
1144 cmLocalUnixMakefileGenerator3::AppendEcho(std::vector<std::string>& commands,
1145 const char* text,
1146 EchoColor color)
1148 // Choose the color for the text.
1149 std::string color_name;
1150 #ifdef CMAKE_BUILD_WITH_CMAKE
1151 if(this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile)
1153 // See cmake::ExecuteEchoColor in cmake.cxx for these options.
1154 // This color set is readable on both black and white backgrounds.
1155 switch(color)
1157 case EchoNormal:
1158 break;
1159 case EchoDepend:
1160 color_name = "--magenta --bold ";
1161 break;
1162 case EchoBuild:
1163 color_name = "--green ";
1164 break;
1165 case EchoLink:
1166 color_name = "--red --bold ";
1167 break;
1168 case EchoGenerate:
1169 color_name = "--blue --bold ";
1170 break;
1171 case EchoGlobal:
1172 color_name = "--cyan ";
1173 break;
1176 #else
1177 (void)color;
1178 #endif
1180 // Echo one line at a time.
1181 std::string line;
1182 line.reserve(200);
1183 for(const char* c = text;; ++c)
1185 if(*c == '\n' || *c == '\0')
1187 // Avoid writing a blank last line on end-of-string.
1188 if(*c != '\0' || !line.empty())
1190 // Add a command to echo this line.
1191 std::string cmd;
1192 if(color_name.empty())
1194 // Use the native echo command.
1195 cmd = this->NativeEchoCommand;
1196 cmd += this->EscapeForShell(line.c_str(), false,
1197 this->NativeEchoWindows);
1199 else
1201 // Use cmake to echo the text in color.
1202 cmd = "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ";
1203 cmd += color_name;
1204 cmd += this->EscapeForShell(line.c_str());
1206 commands.push_back(cmd);
1209 // Reset the line to emtpy.
1210 line = "";
1212 // Terminate on end-of-string.
1213 if(*c == '\0')
1215 return;
1218 else if(*c != '\r')
1220 // Append this character to the current line.
1221 line += *c;
1226 //----------------------------------------------------------------------------
1227 std::string
1228 cmLocalUnixMakefileGenerator3
1229 ::CreateMakeVariable(const char* sin, const char* s2in)
1231 std::string s = sin;
1232 std::string s2 = s2in;
1233 std::string unmodified = s;
1234 unmodified += s2;
1235 // if there is no restriction on the length of make variables
1236 // and there are no "." charactors in the string, then return the
1237 // unmodified combination.
1238 if((!this->MakefileVariableSize && unmodified.find('.') == s.npos)
1239 && (!this->MakefileVariableSize && unmodified.find('-') == s.npos))
1241 return unmodified;
1244 // see if the variable has been defined before and return
1245 // the modified version of the variable
1246 std::map<cmStdString, cmStdString>::iterator i =
1247 this->MakeVariableMap.find(unmodified);
1248 if(i != this->MakeVariableMap.end())
1250 return i->second;
1252 // start with the unmodified variable
1253 std::string ret = unmodified;
1254 // if this there is no value for this->MakefileVariableSize then
1255 // the string must have bad characters in it
1256 if(!this->MakefileVariableSize)
1258 cmSystemTools::ReplaceString(ret, ".", "_");
1259 cmSystemTools::ReplaceString(ret, "-", "__");
1260 int ni = 0;
1261 char buffer[5];
1262 // make sure the _ version is not already used, if
1263 // it is used then add number to the end of the variable
1264 while(this->ShortMakeVariableMap.count(ret) && ni < 1000)
1266 ++ni;
1267 sprintf(buffer, "%04d", ni);
1268 ret = unmodified + buffer;
1270 this->ShortMakeVariableMap[ret] = "1";
1271 this->MakeVariableMap[unmodified] = ret;
1272 return ret;
1275 // if the string is greater the 32 chars it is an invalid vairable name
1276 // for borland make
1277 if(static_cast<int>(ret.size()) > this->MakefileVariableSize)
1279 int keep = this->MakefileVariableSize - 8;
1280 int size = keep + 3;
1281 std::string str1 = s;
1282 std::string str2 = s2;
1283 // we must shorten the combined string by 4 charactors
1284 // keep no more than 24 charactors from the second string
1285 if(static_cast<int>(str2.size()) > keep)
1287 str2 = str2.substr(0, keep);
1289 if(static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size)
1291 str1 = str1.substr(0, size - str2.size());
1293 char buffer[5];
1294 int ni = 0;
1295 sprintf(buffer, "%04d", ni);
1296 ret = str1 + str2 + buffer;
1297 while(this->ShortMakeVariableMap.count(ret) && ni < 1000)
1299 ++ni;
1300 sprintf(buffer, "%04d", ni);
1301 ret = str1 + str2 + buffer;
1303 if(ni == 1000)
1305 cmSystemTools::Error("Borland makefile variable length too long");
1306 return unmodified;
1308 // once an unused variable is found
1309 this->ShortMakeVariableMap[ret] = "1";
1311 // always make an entry into the unmodified to variable map
1312 this->MakeVariableMap[unmodified] = ret;
1313 return ret;
1316 //----------------------------------------------------------------------------
1317 bool cmLocalUnixMakefileGenerator3::UpdateDependencies(const char* tgtInfo,
1318 bool verbose,
1319 bool color)
1321 // read in the target info file
1322 if(!this->Makefile->ReadListFile(0, tgtInfo) ||
1323 cmSystemTools::GetErrorOccuredFlag())
1325 cmSystemTools::Error("Target DependInfo.cmake file not found");
1328 // Check if any multiple output pairs have a missing file.
1329 this->CheckMultipleOutputs(verbose);
1331 std::string dir = cmSystemTools::GetFilenamePath(tgtInfo);
1332 std::string internalDependFile = dir + "/depend.internal";
1333 std::string dependFile = dir + "/depend.make";
1335 // If the target DependInfo.cmake file has changed since the last
1336 // time dependencies were scanned then force rescanning. This may
1337 // happen when a new source file is added and CMake regenerates the
1338 // project but no other sources were touched.
1339 bool needRescan = false;
1340 cmFileTimeComparison* ftc =
1341 this->GlobalGenerator->GetCMakeInstance()->GetFileComparison();
1343 int result;
1344 if(!ftc->FileTimeCompare(internalDependFile.c_str(), tgtInfo, &result) ||
1345 result < 0)
1347 if(verbose)
1349 cmOStringStream msg;
1350 msg << "Dependee \"" << tgtInfo
1351 << "\" is newer than depender \""
1352 << internalDependFile << "\"." << std::endl;
1353 cmSystemTools::Stdout(msg.str().c_str());
1355 needRescan = true;
1359 // Check the implicit dependencies to see if they are up to date.
1360 // The build.make file may have explicit dependencies for the object
1361 // files but these will not affect the scanning process so they need
1362 // not be considered.
1363 cmDependsC checker;
1364 checker.SetVerbose(verbose);
1365 checker.SetFileComparison(ftc);
1366 if(needRescan ||
1367 !checker.Check(dependFile.c_str(), internalDependFile.c_str()))
1369 // The dependencies must be regenerated.
1370 std::string targetName = cmSystemTools::GetFilenameName(dir);
1371 targetName = targetName.substr(0, targetName.length()-4);
1372 std::string message = "Scanning dependencies of target ";
1373 message += targetName;
1374 #ifdef CMAKE_BUILD_WITH_CMAKE
1375 cmSystemTools::MakefileColorEcho(
1376 cmsysTerminal_Color_ForegroundMagenta |
1377 cmsysTerminal_Color_ForegroundBold,
1378 message.c_str(), true, color);
1379 #else
1380 fprintf(stdout, "%s\n", message.c_str());
1381 #endif
1383 return this->ScanDependencies(dir.c_str());
1385 else
1387 // The dependencies are already up-to-date.
1388 return true;
1392 //----------------------------------------------------------------------------
1393 bool
1394 cmLocalUnixMakefileGenerator3
1395 ::ScanDependencies(const char* targetDir)
1397 // Read the directory information file.
1398 cmMakefile* mf = this->Makefile;
1399 bool haveDirectoryInfo = false;
1400 std::string dirInfoFile = this->Makefile->GetStartOutputDirectory();
1401 dirInfoFile += cmake::GetCMakeFilesDirectory();
1402 dirInfoFile += "/CMakeDirectoryInformation.cmake";
1403 if(mf->ReadListFile(0, dirInfoFile.c_str()) &&
1404 !cmSystemTools::GetErrorOccuredFlag())
1406 haveDirectoryInfo = true;
1409 // Lookup useful directory information.
1410 if(haveDirectoryInfo)
1412 // Test whether we need to force Unix paths.
1413 if(const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS"))
1415 if(!cmSystemTools::IsOff(force))
1417 cmSystemTools::SetForceUnixPaths(true);
1421 // Setup relative path top directories.
1422 this->RelativePathsConfigured = true;
1423 if(const char* relativePathTopSource =
1424 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE"))
1426 this->RelativePathTopSource = relativePathTopSource;
1428 if(const char* relativePathTopBinary =
1429 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY"))
1431 this->RelativePathTopBinary = relativePathTopBinary;
1434 else
1436 cmSystemTools::Error("Directory Information file not found");
1439 // create the file stream for the depends file
1440 std::string dir = targetDir;
1442 // Open the make depends file. This should be copy-if-different
1443 // because the make tool may try to reload it needlessly otherwise.
1444 std::string ruleFileNameFull = dir;
1445 ruleFileNameFull += "/depend.make";
1446 cmGeneratedFileStream ruleFileStream(ruleFileNameFull.c_str());
1447 ruleFileStream.SetCopyIfDifferent(true);
1448 if(!ruleFileStream)
1450 return false;
1453 // Open the cmake dependency tracking file. This should not be
1454 // copy-if-different because dependencies are re-scanned when it is
1455 // older than the DependInfo.cmake.
1456 std::string internalRuleFileNameFull = dir;
1457 internalRuleFileNameFull += "/depend.internal";
1458 cmGeneratedFileStream
1459 internalRuleFileStream(internalRuleFileNameFull.c_str());
1460 if(!internalRuleFileStream)
1462 return false;
1465 this->WriteDisclaimer(ruleFileStream);
1466 this->WriteDisclaimer(internalRuleFileStream);
1468 // for each language we need to scan, scan it
1469 const char *langStr = mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES");
1470 std::vector<std::string> langs;
1471 cmSystemTools::ExpandListArgument(langStr, langs);
1472 for (std::vector<std::string>::iterator li =
1473 langs.begin(); li != langs.end(); ++li)
1475 // construct the checker
1476 std::string lang = li->c_str();
1478 // Create the scanner for this language
1479 cmDepends *scanner = 0;
1480 if(lang == "C" || lang == "CXX" || lang == "RC")
1482 // TODO: Handle RC (resource files) dependencies correctly.
1483 scanner = new cmDependsC(this, targetDir, lang.c_str());
1485 #ifdef CMAKE_BUILD_WITH_CMAKE
1486 else if(lang == "Fortran")
1488 scanner = new cmDependsFortran(this);
1490 else if(lang == "Java")
1492 scanner = new cmDependsJava();
1494 #endif
1496 if (scanner)
1498 scanner->SetLocalGenerator(this);
1499 scanner->SetFileComparison
1500 (this->GlobalGenerator->GetCMakeInstance()->GetFileComparison());
1501 scanner->SetLanguage(lang.c_str());
1502 scanner->SetTargetDirectory(dir.c_str());
1503 scanner->Write(ruleFileStream, internalRuleFileStream);
1505 // free the scanner for this language
1506 delete scanner;
1510 return true;
1513 //----------------------------------------------------------------------------
1514 void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
1516 cmMakefile* mf = this->Makefile;
1518 // Get the string listing the multiple output pairs.
1519 const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
1520 if(!pairs_string)
1522 return;
1525 // Convert the string to a list and preserve empty entries.
1526 std::vector<std::string> pairs;
1527 cmSystemTools::ExpandListArgument(pairs_string, pairs, true);
1528 for(std::vector<std::string>::const_iterator i = pairs.begin();
1529 i != pairs.end() && (i+1) != pairs.end();)
1531 const std::string& depender = *i++;
1532 const std::string& dependee = *i++;
1534 // If the depender is missing then delete the dependee to make
1535 // sure both will be regenerated.
1536 if(cmSystemTools::FileExists(dependee.c_str()) &&
1537 !cmSystemTools::FileExists(depender.c_str()))
1539 if(verbose)
1541 cmOStringStream msg;
1542 msg << "Deleting primary custom command output \"" << dependee
1543 << "\" because another output \""
1544 << depender << "\" does not exist." << std::endl;
1545 cmSystemTools::Stdout(msg.str().c_str());
1547 cmSystemTools::RemoveFile(dependee.c_str());
1552 //----------------------------------------------------------------------------
1553 void cmLocalUnixMakefileGenerator3
1554 ::WriteLocalAllRules(std::ostream& ruleFileStream)
1556 this->WriteDisclaimer(ruleFileStream);
1558 // Write the main entry point target. This must be the VERY first
1559 // target so that make with no arguments will run it.
1561 // Just depend on the all target to drive the build.
1562 std::vector<std::string> depends;
1563 std::vector<std::string> no_commands;
1564 depends.push_back("all");
1566 // Write the rule.
1567 this->WriteMakeRule(ruleFileStream,
1568 "Default target executed when no arguments are "
1569 "given to make.",
1570 "default_target",
1571 depends,
1572 no_commands, true);
1575 this->WriteSpecialTargetsTop(ruleFileStream);
1577 // Include the progress variables for the target.
1578 // Write all global targets
1579 this->WriteDivider(ruleFileStream);
1580 ruleFileStream
1581 << "# Targets provided globally by CMake.\n"
1582 << "\n";
1583 cmTargets* targets = &(this->Makefile->GetTargets());
1584 cmTargets::iterator glIt;
1585 for ( glIt = targets->begin(); glIt != targets->end(); ++ glIt )
1587 if ( glIt->second.GetType() == cmTarget::GLOBAL_TARGET )
1589 std::string targetString = "Special rule for the target " + glIt->first;
1590 std::vector<std::string> commands;
1591 std::vector<std::string> depends;
1593 const char* text = glIt->second.GetProperty("EchoString");
1594 if ( !text )
1596 text = "Running external command ...";
1598 std::set<cmStdString>::const_iterator dit;
1599 for ( dit = glIt->second.GetUtilities().begin();
1600 dit != glIt->second.GetUtilities().end();
1601 ++ dit )
1603 depends.push_back(dit->c_str());
1605 this->AppendEcho(commands, text,
1606 cmLocalUnixMakefileGenerator3::EchoGlobal);
1608 // Global targets store their rules in pre- and post-build commands.
1609 this->AppendCustomDepends(depends,
1610 glIt->second.GetPreBuildCommands());
1611 this->AppendCustomDepends(depends,
1612 glIt->second.GetPostBuildCommands());
1613 this->AppendCustomCommands(commands,
1614 glIt->second.GetPreBuildCommands(),
1615 cmLocalGenerator::START_OUTPUT);
1616 this->AppendCustomCommands(commands,
1617 glIt->second.GetPostBuildCommands(),
1618 cmLocalGenerator::START_OUTPUT);
1619 std::string targetName = glIt->second.GetName();
1620 this->WriteMakeRule(ruleFileStream, targetString.c_str(),
1621 targetName.c_str(), depends, commands, true);
1623 // Provide a "/fast" version of the target.
1624 depends.clear();
1625 if((targetName == "install")
1626 || (targetName == "install_local")
1627 || (targetName == "install_strip"))
1629 // Provide a fast install target that does not depend on all
1630 // but has the same command.
1631 depends.push_back("preinstall/fast");
1633 else
1635 // Just forward to the real target so at least it will work.
1636 depends.push_back(targetName);
1637 commands.clear();
1639 targetName += "/fast";
1640 this->WriteMakeRule(ruleFileStream, targetString.c_str(),
1641 targetName.c_str(), depends, commands, true);
1645 std::vector<std::string> depends;
1646 std::vector<std::string> commands;
1648 // Write the all rule.
1649 std::string dir;
1650 std::string recursiveTarget = this->Makefile->GetStartOutputDirectory();
1651 recursiveTarget += "/all";
1653 depends.push_back("cmake_check_build_system");
1655 std::string progressDir = this->Makefile->GetHomeOutputDirectory();
1656 progressDir += cmake::GetCMakeFilesDirectory();
1658 cmOStringStream progCmd;
1659 progCmd <<
1660 "$(CMAKE_COMMAND) -E cmake_progress_start ";
1661 progCmd << this->Convert(progressDir.c_str(),
1662 cmLocalGenerator::FULL,
1663 cmLocalGenerator::SHELL);
1665 std::string progressFile = cmake::GetCMakeFilesDirectory();
1666 progressFile += "/progress.make";
1667 std::string progressFileNameFull =
1668 this->ConvertToFullPath(progressFile.c_str());
1669 progCmd << " " << this->Convert(progressFileNameFull.c_str(),
1670 cmLocalGenerator::FULL,
1671 cmLocalGenerator::SHELL);
1672 commands.push_back(progCmd.str());
1674 std::string mf2Dir = cmake::GetCMakeFilesDirectoryPostSlash();
1675 mf2Dir += "Makefile2";
1676 commands.push_back(this->GetRecursiveMakeCall(mf2Dir.c_str(),
1677 recursiveTarget.c_str()));
1678 this->CreateCDCommand(commands,
1679 this->Makefile->GetHomeOutputDirectory(),
1680 cmLocalGenerator::START_OUTPUT);
1682 cmOStringStream progCmd;
1683 progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
1684 progCmd << this->Convert(progressDir.c_str(),
1685 cmLocalGenerator::FULL,
1686 cmLocalGenerator::SHELL);
1687 progCmd << " 0";
1688 commands.push_back(progCmd.str());
1690 this->WriteMakeRule(ruleFileStream, "The main all target", "all",
1691 depends, commands, true);
1693 // Write the clean rule.
1694 recursiveTarget = this->Makefile->GetStartOutputDirectory();
1695 recursiveTarget += "/clean";
1696 commands.clear();
1697 depends.clear();
1698 commands.push_back(this->GetRecursiveMakeCall(mf2Dir.c_str(),
1699 recursiveTarget.c_str()));
1700 this->CreateCDCommand(commands,
1701 this->Makefile->GetHomeOutputDirectory(),
1702 cmLocalGenerator::START_OUTPUT);
1703 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
1704 depends, commands, true);
1705 commands.clear();
1706 depends.clear();
1707 depends.push_back("clean");
1708 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
1709 depends, commands, true);
1711 // Write the preinstall rule.
1712 recursiveTarget = this->Makefile->GetStartOutputDirectory();
1713 recursiveTarget += "/preinstall";
1714 commands.clear();
1715 depends.clear();
1716 const char* noall =
1717 this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
1718 if(!noall || cmSystemTools::IsOff(noall))
1720 // Drive the build before installing.
1721 depends.push_back("all");
1723 else
1725 // At least make sure the build system is up to date.
1726 depends.push_back("cmake_check_build_system");
1728 commands.push_back
1729 (this->GetRecursiveMakeCall(mf2Dir.c_str(), recursiveTarget.c_str()));
1730 this->CreateCDCommand(commands,
1731 this->Makefile->GetHomeOutputDirectory(),
1732 cmLocalGenerator::START_OUTPUT);
1733 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1734 "preinstall", depends, commands, true);
1735 depends.clear();
1736 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1737 "preinstall/fast", depends, commands, true);
1739 // write the depend rule, really a recompute depends rule
1740 depends.clear();
1741 commands.clear();
1742 std::string cmakefileName = cmake::GetCMakeFilesDirectoryPostSlash();
1743 cmakefileName += "Makefile.cmake";
1744 std::string runRule =
1745 "$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
1746 runRule += " --check-build-system ";
1747 runRule += this->Convert(cmakefileName.c_str(),cmLocalGenerator::NONE,
1748 cmLocalGenerator::SHELL);
1749 runRule += " 1";
1750 commands.push_back(runRule);
1751 this->CreateCDCommand(commands,
1752 this->Makefile->GetHomeOutputDirectory(),
1753 cmLocalGenerator::START_OUTPUT);
1754 this->WriteMakeRule(ruleFileStream, "clear depends",
1755 "depend",
1756 depends, commands, true);
1760 //----------------------------------------------------------------------------
1761 void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
1762 bool verbose)
1764 // Get the list of target files to check
1765 const char* infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
1766 if(!infoDef)
1768 return;
1770 std::vector<std::string> files;
1771 cmSystemTools::ExpandListArgument(infoDef, files);
1773 // Each depend information file corresponds to a target. Clear the
1774 // dependencies for that target.
1775 cmDepends clearer;
1776 clearer.SetVerbose(verbose);
1777 for(std::vector<std::string>::iterator l = files.begin();
1778 l != files.end(); ++l)
1780 std::string dir = cmSystemTools::GetFilenamePath(l->c_str());
1782 // Clear the implicit dependency makefile.
1783 std::string dependFile = dir + "/depend.make";
1784 clearer.Clear(dependFile.c_str());
1786 // Remove the internal dependency check file to force
1787 // regeneration.
1788 std::string internalDependFile = dir + "/depend.internal";
1789 cmSystemTools::RemoveFile(internalDependFile.c_str());
1794 void cmLocalUnixMakefileGenerator3
1795 ::WriteDependLanguageInfo(std::ostream& cmakefileStream, cmTarget &target)
1797 ImplicitDependLanguageMap const& implicitLangs =
1798 this->GetImplicitDepends(target);
1800 // list the languages
1801 cmakefileStream
1802 << "# The set of languages for which implicit dependencies are needed:\n";
1803 cmakefileStream
1804 << "SET(CMAKE_DEPENDS_LANGUAGES\n";
1805 for(ImplicitDependLanguageMap::const_iterator
1806 l = implicitLangs.begin(); l != implicitLangs.end(); ++l)
1808 cmakefileStream << " \"" << l->first.c_str() << "\"\n";
1810 cmakefileStream << " )\n";
1812 // now list the files for each language
1813 cmakefileStream
1814 << "# The set of files for implicit dependencies of each language:\n";
1815 for(ImplicitDependLanguageMap::const_iterator
1816 l = implicitLangs.begin(); l != implicitLangs.end(); ++l)
1818 cmakefileStream
1819 << "SET(CMAKE_DEPENDS_CHECK_" << l->first.c_str() << "\n";
1820 ImplicitDependFileMap const& implicitPairs = l->second;
1822 // for each file pair
1823 for(ImplicitDependFileMap::const_iterator pi = implicitPairs.begin();
1824 pi != implicitPairs.end(); ++pi)
1826 cmakefileStream << " \"" << pi->second << "\" ";
1827 cmakefileStream << "\"" << pi->first << "\"\n";
1829 cmakefileStream << " )\n";
1831 // Tell the dependency scanner what compiler is used.
1832 std::string cidVar = "CMAKE_";
1833 cidVar += l->first;
1834 cidVar += "_COMPILER_ID";
1835 const char* cid = this->Makefile->GetDefinition(cidVar.c_str());
1836 if(cid && *cid)
1838 cmakefileStream
1839 << "SET(CMAKE_" << l->first.c_str() << "_COMPILER_ID \""
1840 << cid << "\")\n";
1844 // Build a list of preprocessor definitions for the target.
1845 std::vector<std::string> defines;
1847 std::string defPropName = "COMPILE_DEFINITIONS_";
1848 defPropName += cmSystemTools::UpperCase(this->ConfigurationName);
1849 if(const char* ddefs = this->Makefile->GetProperty("COMPILE_DEFINITIONS"))
1851 cmSystemTools::ExpandListArgument(ddefs, defines);
1853 if(const char* cdefs = target.GetProperty("COMPILE_DEFINITIONS"))
1855 cmSystemTools::ExpandListArgument(cdefs, defines);
1857 if(const char* dcdefs = this->Makefile->GetProperty(defPropName.c_str()))
1859 cmSystemTools::ExpandListArgument(dcdefs, defines);
1861 if(const char* ccdefs = target.GetProperty(defPropName.c_str()))
1863 cmSystemTools::ExpandListArgument(ccdefs, defines);
1866 if(!defines.empty())
1868 cmakefileStream
1869 << "\n"
1870 << "# Preprocessor definitions for this target.\n"
1871 << "SET(CMAKE_TARGET_DEFINITIONS\n";
1872 for(std::vector<std::string>::const_iterator di = defines.begin();
1873 di != defines.end(); ++di)
1875 cmakefileStream
1876 << " " << this->EscapeForCMake(di->c_str()) << "\n";
1878 cmakefileStream
1879 << " )\n";
1882 // Store include transform rule properties. Write the directory
1883 // rules first because they may be overridden by later target rules.
1884 std::vector<std::string> transformRules;
1885 if(const char* xform =
1886 this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM"))
1888 cmSystemTools::ExpandListArgument(xform, transformRules);
1890 if(const char* xform =
1891 target.GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM"))
1893 cmSystemTools::ExpandListArgument(xform, transformRules);
1895 if(!transformRules.empty())
1897 cmakefileStream
1898 << "SET(CMAKE_INCLUDE_TRANSFORMS\n";
1899 for(std::vector<std::string>::const_iterator tri = transformRules.begin();
1900 tri != transformRules.end(); ++tri)
1902 cmakefileStream << " " << this->EscapeForCMake(tri->c_str()) << "\n";
1904 cmakefileStream
1905 << " )\n";
1909 //----------------------------------------------------------------------------
1910 std::string
1911 cmLocalUnixMakefileGenerator3
1912 ::GetObjectFileName(cmTarget& target,
1913 const cmSourceFile& source,
1914 std::string* nameWithoutTargetDir,
1915 bool* hasSourceExtension)
1917 // Make sure we never hit this old case.
1918 if(source.GetProperty("MACOSX_PACKAGE_LOCATION"))
1920 std::string msg = "MACOSX_PACKAGE_LOCATION set on source file: ";
1921 msg += source.GetFullPath();
1922 this->GetMakefile()->IssueMessage(cmake::INTERNAL_ERROR,
1923 msg.c_str());
1926 // Start with the target directory.
1927 std::string obj = this->GetTargetDirectory(target);
1928 obj += "/";
1930 // Get the object file name without the target directory.
1931 std::string::size_type dir_len = 0;
1932 dir_len += strlen(this->Makefile->GetCurrentOutputDirectory());
1933 dir_len += 1;
1934 dir_len += obj.size();
1935 std::string objectName =
1936 this->GetObjectFileNameWithoutTarget(source, dir_len,
1937 hasSourceExtension);
1938 if(nameWithoutTargetDir)
1940 *nameWithoutTargetDir = objectName;
1943 // Append the object name to the target directory.
1944 obj += objectName;
1945 return obj;
1948 //----------------------------------------------------------------------------
1949 void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
1952 << "# CMAKE generated file: DO NOT EDIT!\n"
1953 << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
1954 << " Generator, CMake Version "
1955 << cmVersion::GetMajorVersion() << "."
1956 << cmVersion::GetMinorVersion() << "\n\n";
1959 //----------------------------------------------------------------------------
1960 std::string
1961 cmLocalUnixMakefileGenerator3
1962 ::GetRecursiveMakeCall(const char *makefile, const char* tgt)
1964 // Call make on the given file.
1965 std::string cmd;
1966 cmd += "$(MAKE) -f ";
1967 cmd += this->Convert(makefile,NONE,SHELL);
1968 cmd += " ";
1970 // Passg down verbosity level.
1971 if(this->GetMakeSilentFlag().size())
1973 cmd += this->GetMakeSilentFlag();
1974 cmd += " ";
1977 // Most unix makes will pass the command line flags to make down to
1978 // sub-invoked makes via an environment variable. However, some
1979 // makes do not support that, so you have to pass the flags
1980 // explicitly.
1981 if(this->GetPassMakeflags())
1983 cmd += "-$(MAKEFLAGS) ";
1986 // Add the target.
1987 if (tgt && tgt[0] != '\0')
1989 // The make target is always relative to the top of the build tree.
1990 std::string tgt2 = this->Convert(tgt, HOME_OUTPUT);
1992 // The target may have been written with windows paths.
1993 cmSystemTools::ConvertToOutputSlashes(tgt2);
1995 // Escape one extra time if the make tool requires it.
1996 if(this->MakeCommandEscapeTargetTwice)
1998 tgt2 = this->EscapeForShell(tgt2.c_str(), true, false);
2001 // The target name is now a string that should be passed verbatim
2002 // on the command line.
2003 cmd += this->EscapeForShell(tgt2.c_str(), true, false);
2005 return cmd;
2008 //----------------------------------------------------------------------------
2009 void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
2012 << "#======================================"
2013 << "=======================================\n";
2016 //----------------------------------------------------------------------------
2017 void
2018 cmLocalUnixMakefileGenerator3
2019 ::WriteCMakeArgument(std::ostream& os, const char* s)
2021 // Write the given string to the stream with escaping to get it back
2022 // into CMake through the lexical scanner.
2023 os << "\"";
2024 for(const char* c = s; *c; ++c)
2026 if(*c == '\\')
2028 os << "\\\\";
2030 else if(*c == '"')
2032 os << "\\\"";
2034 else
2036 os << *c;
2039 os << "\"";
2042 //----------------------------------------------------------------------------
2043 std::string
2044 cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(const char* p)
2047 // Split the path into its components.
2048 std::vector<std::string> components;
2049 cmSystemTools::SplitPath(p, components);
2051 // Return an empty path if there are no components.
2052 if(components.empty())
2054 return "\"\"";
2057 // Choose a slash direction and fix root component.
2058 const char* slash = "/";
2059 #if defined(_WIN32) && !defined(__CYGWIN__)
2060 if(!cmSystemTools::GetForceUnixPaths())
2062 slash = "\\";
2063 for(std::string::iterator i = components[0].begin();
2064 i != components[0].end(); ++i)
2066 if(*i == '/')
2068 *i = '\\';
2072 #endif
2074 // Begin the quoted result with the root component.
2075 std::string result = "\"";
2076 result += components[0];
2078 // Now add the rest of the components separated by the proper slash
2079 // direction for this platform.
2080 bool first = true;
2081 for(unsigned int i=1; i < components.size(); ++i)
2083 // Only the last component can be empty to avoid double slashes.
2084 if(components[i].length() > 0 || (i == (components.size()-1)))
2086 if(!first)
2088 result += slash;
2090 result += components[i];
2091 first = false;
2095 // Close the quoted result.
2096 result += "\"";
2098 return result;
2101 //----------------------------------------------------------------------------
2102 std::string
2103 cmLocalUnixMakefileGenerator3
2104 ::GetTargetDirectory(cmTarget const& target) const
2106 std::string dir = cmake::GetCMakeFilesDirectoryPostSlash();
2107 dir += target.GetName();
2108 dir += ".dir";
2109 return dir;
2112 //----------------------------------------------------------------------------
2113 cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
2114 cmLocalUnixMakefileGenerator3::GetImplicitDepends(cmTarget const& tgt)
2116 return this->ImplicitDepends[tgt.GetName()];
2119 //----------------------------------------------------------------------------
2120 void
2121 cmLocalUnixMakefileGenerator3::AddImplicitDepends(cmTarget const& tgt,
2122 const char* lang,
2123 const char* obj,
2124 const char* src)
2126 this->ImplicitDepends[tgt.GetName()][lang][obj] = src;
2129 //----------------------------------------------------------------------------
2130 void cmLocalUnixMakefileGenerator3
2131 ::CreateCDCommand(std::vector<std::string>& commands, const char *tgtDir,
2132 cmLocalGenerator::RelativeRoot relRetDir)
2134 const char* retDir = this->GetRelativeRootPath(relRetDir);
2136 // do we need to cd?
2137 if (!strcmp(tgtDir,retDir))
2139 return;
2142 if(!this->UnixCD)
2144 // On Windows we must perform each step separately and then change
2145 // back because the shell keeps the working directory between
2146 // commands.
2147 std::string cmd = "cd ";
2148 cmd += this->ConvertToOutputForExisting(tgtDir, relRetDir);
2149 commands.insert(commands.begin(),cmd);
2151 // Change back to the starting directory.
2152 cmd = "cd ";
2153 cmd += this->ConvertToOutputForExisting(relRetDir, tgtDir);
2154 commands.push_back(cmd);
2156 else
2158 // On UNIX we must construct a single shell command to change
2159 // directory and build because make resets the directory between
2160 // each command.
2161 std::vector<std::string>::iterator i = commands.begin();
2162 for (; i != commands.end(); ++i)
2164 std::string cmd = "cd ";
2165 cmd += this->ConvertToOutputForExisting(tgtDir, relRetDir);
2166 cmd += " && ";
2167 cmd += *i;
2168 *i = cmd;
2174 void cmLocalUnixMakefileGenerator3
2175 ::GetTargetObjectFileDirectories(cmTarget* target,
2176 std::vector<std::string>& dirs)
2178 std::string dir = this->Makefile->GetCurrentOutputDirectory();
2179 dir += "/";
2180 dir += this->GetTargetDirectory(*target);
2181 dirs.push_back(dir);