STYLE: Nightly Date Stamp
[cmake.git] / Source / cmLocalUnixMakefileGenerator3.cxx
blobf43dca630c8804c535ccc12cc9eca9b0763e1b17
1 /*=========================================================================
3 Program: CMake - Cross-Platform Makefile Generator
4 Module: $RCSfile: cmLocalUnixMakefileGenerator3.cxx,v $
5 Language: C++
6 Date: $Date: 2008-05-14 15:54:52 $
7 Version: $Revision: 1.252 $
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())
361 this->CreateCDCommand(commands,
362 this->Makefile->GetHomeOutputDirectory(),
363 this->Makefile->GetStartOutputDirectory());
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 this->Makefile->GetStartOutputDirectory());
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 this->Makefile->GetStartOutputDirectory());
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 this->Makefile->GetStartOutputDirectory());
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(this->Makefile->GetDefinition("CMAKE_EDIT_COMMAND"))
702 makefileStream
703 << "# The program to use to edit the cache.\n"
704 << "CMAKE_EDIT_COMMAND = "
705 << (this->ConvertToOutputForExisting(
706 this->Makefile->GetDefinition("CMAKE_EDIT_COMMAND"))) << "\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 this->Makefile->GetStartOutputDirectory());
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)
958 for(std::vector<cmCustomCommand>::const_iterator i = ccs.begin();
959 i != ccs.end(); ++i)
961 this->AppendCustomCommand(commands, *i, true);
965 //----------------------------------------------------------------------------
966 void
967 cmLocalUnixMakefileGenerator3
968 ::AppendCustomCommand(std::vector<std::string>& commands,
969 const cmCustomCommand& cc, bool echo_comment)
971 // Optionally create a command to display the custom command's
972 // comment text. This is used for pre-build, pre-link, and
973 // post-build command comments. Custom build step commands have
974 // their comments generated elsewhere.
975 if(echo_comment)
977 const char* comment = cc.GetComment();
978 if(comment && *comment)
980 this->AppendEcho(commands, comment,
981 cmLocalUnixMakefileGenerator3::EchoGenerate);
985 // if the command specified a working directory use it.
986 const char* dir = this->Makefile->GetStartOutputDirectory();
987 const char* workingDir = cc.GetWorkingDirectory();
988 if(workingDir)
990 dir = workingDir;
992 bool escapeOldStyle = cc.GetEscapeOldStyle();
993 bool escapeAllowMakeVars = cc.GetEscapeAllowMakeVars();
995 // Add each command line to the set of commands.
996 std::vector<std::string> commands1;
997 for(cmCustomCommandLines::const_iterator cl = cc.GetCommandLines().begin();
998 cl != cc.GetCommandLines().end(); ++cl)
1000 // Build the command line in a single string.
1001 const cmCustomCommandLine& commandLine = *cl;
1002 std::string cmd = GetRealLocation(commandLine[0].c_str(),
1003 this->ConfigurationName.c_str());
1004 if (cmd.size())
1006 cmSystemTools::ReplaceString(cmd, "/./", "/");
1007 // Convert the command to a relative path only if the current
1008 // working directory will be the start-output directory.
1009 bool had_slash = cmd.find("/") != cmd.npos;
1010 if(!workingDir)
1012 cmd = this->Convert(cmd.c_str(),START_OUTPUT);
1014 bool has_slash = cmd.find("/") != cmd.npos;
1015 if(had_slash && !has_slash)
1017 // This command was specified as a path to a file in the
1018 // current directory. Add a leading "./" so it can run
1019 // without the current directory being in the search path.
1020 cmd = "./" + cmd;
1022 if(this->WatcomWMake &&
1023 cmSystemTools::FileIsFullPath(cmd.c_str()) &&
1024 cmd.find(" ") != cmd.npos)
1026 // On Watcom WMake use the windows short path for the command
1027 // name. This is needed to avoid funny quoting problems on
1028 // lines with shell redirection operators.
1029 std::string scmd;
1030 if(cmSystemTools::GetShortPath(cmd.c_str(), scmd))
1032 cmd = scmd;
1035 cmd = this->Convert(cmd.c_str(),NONE,SHELL);
1036 for(unsigned int j=1; j < commandLine.size(); ++j)
1038 cmd += " ";
1039 if(escapeOldStyle)
1041 cmd += this->EscapeForShellOldStyle(commandLine[j].c_str());
1043 else
1045 cmd += this->EscapeForShell(commandLine[j].c_str(),
1046 escapeAllowMakeVars);
1049 if(this->BorlandMakeCurlyHack)
1051 // Borland Make has a very strange bug. If the first curly
1052 // brace anywhere in the command string is a left curly, it
1053 // must be written {{} instead of just {. Otherwise some
1054 // curly braces are removed. The hack can be skipped if the
1055 // first curly brace is the last character.
1056 std::string::size_type lcurly = cmd.find("{");
1057 if(lcurly != cmd.npos && lcurly < (cmd.size()-1))
1059 std::string::size_type rcurly = cmd.find("}");
1060 if(rcurly == cmd.npos || rcurly > lcurly)
1062 // The first curly is a left curly. Use the hack.
1063 std::string hack_cmd = cmd.substr(0, lcurly);
1064 hack_cmd += "{{}";
1065 hack_cmd += cmd.substr(lcurly+1);
1066 cmd = hack_cmd;
1070 commands1.push_back(cmd);
1074 // Setup the proper working directory for the commands.
1075 this->CreateCDCommand(commands1, dir,
1076 this->Makefile->GetHomeOutputDirectory());
1078 // push back the custom commands
1079 commands.insert(commands.end(), commands1.begin(), commands1.end());
1082 //----------------------------------------------------------------------------
1083 void
1084 cmLocalUnixMakefileGenerator3
1085 ::AppendCleanCommand(std::vector<std::string>& commands,
1086 const std::vector<std::string>& files,
1087 cmTarget& target, const char* filename)
1089 if(!files.empty())
1091 std::string cleanfile = this->Makefile->GetCurrentOutputDirectory();
1092 cleanfile += "/";
1093 cleanfile += this->GetTargetDirectory(target);
1094 cleanfile += "/cmake_clean";
1095 if(filename)
1097 cleanfile += "_";
1098 cleanfile += filename;
1100 cleanfile += ".cmake";
1101 std::string cleanfilePath = this->Convert(cleanfile.c_str(), FULL);
1102 std::ofstream fout(cleanfilePath.c_str());
1103 if(!fout)
1105 cmSystemTools::Error("Could not create ", cleanfilePath.c_str());
1107 fout << "FILE(REMOVE_RECURSE\n";
1108 std::string remove = "$(CMAKE_COMMAND) -P ";
1109 remove += this->Convert(cleanfile.c_str(), START_OUTPUT, SHELL);
1110 for(std::vector<std::string>::const_iterator f = files.begin();
1111 f != files.end(); ++f)
1113 std::string fc = this->Convert(f->c_str(),START_OUTPUT,UNCHANGED);
1114 fout << " " << this->EscapeForCMake(fc.c_str()) << "\n";
1116 fout << ")\n";
1117 commands.push_back(remove);
1119 // For the main clean rule add per-language cleaning.
1120 if(!filename)
1122 // Get the set of source languages in the target.
1123 std::set<cmStdString> languages;
1124 target.GetLanguages(languages);
1125 fout << "\n"
1126 << "# Per-language clean rules from dependency scanning.\n"
1127 << "FOREACH(lang";
1128 for(std::set<cmStdString>::const_iterator l = languages.begin();
1129 l != languages.end(); ++l)
1131 fout << " " << *l;
1133 fout << ")\n"
1134 << " INCLUDE(" << this->GetTargetDirectory(target)
1135 << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
1136 << "ENDFOREACH(lang)\n";
1141 //----------------------------------------------------------------------------
1142 void
1143 cmLocalUnixMakefileGenerator3::AppendEcho(std::vector<std::string>& commands,
1144 const char* text,
1145 EchoColor color)
1147 // Choose the color for the text.
1148 std::string color_name;
1149 #ifdef CMAKE_BUILD_WITH_CMAKE
1150 if(this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile)
1152 // See cmake::ExecuteEchoColor in cmake.cxx for these options.
1153 // This color set is readable on both black and white backgrounds.
1154 switch(color)
1156 case EchoNormal:
1157 break;
1158 case EchoDepend:
1159 color_name = "--magenta --bold ";
1160 break;
1161 case EchoBuild:
1162 color_name = "--green ";
1163 break;
1164 case EchoLink:
1165 color_name = "--red --bold ";
1166 break;
1167 case EchoGenerate:
1168 color_name = "--blue --bold ";
1169 break;
1170 case EchoGlobal:
1171 color_name = "--cyan ";
1172 break;
1175 #else
1176 (void)color;
1177 #endif
1179 // Echo one line at a time.
1180 std::string line;
1181 line.reserve(200);
1182 for(const char* c = text;; ++c)
1184 if(*c == '\n' || *c == '\0')
1186 // Avoid writing a blank last line on end-of-string.
1187 if(*c != '\0' || !line.empty())
1189 // Add a command to echo this line.
1190 std::string cmd;
1191 if(color_name.empty())
1193 // Use the native echo command.
1194 cmd = this->NativeEchoCommand;
1195 cmd += this->EscapeForShell(line.c_str(), false,
1196 this->NativeEchoWindows);
1198 else
1200 // Use cmake to echo the text in color.
1201 cmd = "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ";
1202 cmd += color_name;
1203 cmd += this->EscapeForShell(line.c_str());
1205 commands.push_back(cmd);
1208 // Reset the line to emtpy.
1209 line = "";
1211 // Terminate on end-of-string.
1212 if(*c == '\0')
1214 return;
1217 else if(*c != '\r')
1219 // Append this character to the current line.
1220 line += *c;
1225 //----------------------------------------------------------------------------
1226 std::string
1227 cmLocalUnixMakefileGenerator3
1228 ::CreateMakeVariable(const char* sin, const char* s2in)
1230 std::string s = sin;
1231 std::string s2 = s2in;
1232 std::string unmodified = s;
1233 unmodified += s2;
1234 // if there is no restriction on the length of make variables
1235 // and there are no "." charactors in the string, then return the
1236 // unmodified combination.
1237 if((!this->MakefileVariableSize && unmodified.find('.') == s.npos)
1238 && (!this->MakefileVariableSize && unmodified.find('-') == s.npos))
1240 return unmodified;
1243 // see if the variable has been defined before and return
1244 // the modified version of the variable
1245 std::map<cmStdString, cmStdString>::iterator i =
1246 this->MakeVariableMap.find(unmodified);
1247 if(i != this->MakeVariableMap.end())
1249 return i->second;
1251 // start with the unmodified variable
1252 std::string ret = unmodified;
1253 // if this there is no value for this->MakefileVariableSize then
1254 // the string must have bad characters in it
1255 if(!this->MakefileVariableSize)
1257 cmSystemTools::ReplaceString(ret, ".", "_");
1258 cmSystemTools::ReplaceString(ret, "-", "__");
1259 int ni = 0;
1260 char buffer[5];
1261 // make sure the _ version is not already used, if
1262 // it is used then add number to the end of the variable
1263 while(this->ShortMakeVariableMap.count(ret) && ni < 1000)
1265 ++ni;
1266 sprintf(buffer, "%04d", ni);
1267 ret = unmodified + buffer;
1269 this->ShortMakeVariableMap[ret] = "1";
1270 this->MakeVariableMap[unmodified] = ret;
1271 return ret;
1274 // if the string is greater the 32 chars it is an invalid vairable name
1275 // for borland make
1276 if(static_cast<int>(ret.size()) > this->MakefileVariableSize)
1278 int keep = this->MakefileVariableSize - 8;
1279 int size = keep + 3;
1280 std::string str1 = s;
1281 std::string str2 = s2;
1282 // we must shorten the combined string by 4 charactors
1283 // keep no more than 24 charactors from the second string
1284 if(static_cast<int>(str2.size()) > keep)
1286 str2 = str2.substr(0, keep);
1288 if(static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size)
1290 str1 = str1.substr(0, size - str2.size());
1292 char buffer[5];
1293 int ni = 0;
1294 sprintf(buffer, "%04d", ni);
1295 ret = str1 + str2 + buffer;
1296 while(this->ShortMakeVariableMap.count(ret) && ni < 1000)
1298 ++ni;
1299 sprintf(buffer, "%04d", ni);
1300 ret = str1 + str2 + buffer;
1302 if(ni == 1000)
1304 cmSystemTools::Error("Borland makefile variable length too long");
1305 return unmodified;
1307 // once an unused variable is found
1308 this->ShortMakeVariableMap[ret] = "1";
1310 // always make an entry into the unmodified to variable map
1311 this->MakeVariableMap[unmodified] = ret;
1312 return ret;
1315 //----------------------------------------------------------------------------
1316 bool cmLocalUnixMakefileGenerator3::UpdateDependencies(const char* tgtInfo,
1317 bool verbose,
1318 bool color)
1320 // read in the target info file
1321 if(!this->Makefile->ReadListFile(0, tgtInfo) ||
1322 cmSystemTools::GetErrorOccuredFlag())
1324 cmSystemTools::Error("Target DependInfo.cmake file not found");
1327 // Check if any multiple output pairs have a missing file.
1328 this->CheckMultipleOutputs(verbose);
1330 std::string dir = cmSystemTools::GetFilenamePath(tgtInfo);
1331 std::string internalDependFile = dir + "/depend.internal";
1332 std::string dependFile = dir + "/depend.make";
1334 // If the target DependInfo.cmake file has changed since the last
1335 // time dependencies were scanned then force rescanning. This may
1336 // happen when a new source file is added and CMake regenerates the
1337 // project but no other sources were touched.
1338 bool needRescan = false;
1339 cmFileTimeComparison* ftc =
1340 this->GlobalGenerator->GetCMakeInstance()->GetFileComparison();
1342 int result;
1343 if(!ftc->FileTimeCompare(internalDependFile.c_str(), tgtInfo, &result) ||
1344 result < 0)
1346 if(verbose)
1348 cmOStringStream msg;
1349 msg << "Dependee \"" << tgtInfo
1350 << "\" is newer than depender \""
1351 << internalDependFile << "\"." << std::endl;
1352 cmSystemTools::Stdout(msg.str().c_str());
1354 needRescan = true;
1358 // Check the implicit dependencies to see if they are up to date.
1359 // The build.make file may have explicit dependencies for the object
1360 // files but these will not affect the scanning process so they need
1361 // not be considered.
1362 cmDependsC checker;
1363 checker.SetVerbose(verbose);
1364 checker.SetFileComparison(ftc);
1365 if(needRescan ||
1366 !checker.Check(dependFile.c_str(), internalDependFile.c_str()))
1368 // The dependencies must be regenerated.
1369 std::string targetName = cmSystemTools::GetFilenameName(dir);
1370 targetName = targetName.substr(0, targetName.length()-4);
1371 std::string message = "Scanning dependencies of target ";
1372 message += targetName;
1373 #ifdef CMAKE_BUILD_WITH_CMAKE
1374 cmSystemTools::MakefileColorEcho(
1375 cmsysTerminal_Color_ForegroundMagenta |
1376 cmsysTerminal_Color_ForegroundBold,
1377 message.c_str(), true, color);
1378 #else
1379 fprintf(stdout, "%s\n", message.c_str());
1380 #endif
1382 return this->ScanDependencies(dir.c_str());
1384 else
1386 // The dependencies are already up-to-date.
1387 return true;
1391 //----------------------------------------------------------------------------
1392 bool
1393 cmLocalUnixMakefileGenerator3
1394 ::ScanDependencies(const char* targetDir)
1396 // Read the directory information file.
1397 cmMakefile* mf = this->Makefile;
1398 bool haveDirectoryInfo = false;
1399 std::string dirInfoFile = this->Makefile->GetStartOutputDirectory();
1400 dirInfoFile += cmake::GetCMakeFilesDirectory();
1401 dirInfoFile += "/CMakeDirectoryInformation.cmake";
1402 if(mf->ReadListFile(0, dirInfoFile.c_str()) &&
1403 !cmSystemTools::GetErrorOccuredFlag())
1405 haveDirectoryInfo = true;
1408 // Lookup useful directory information.
1409 if(haveDirectoryInfo)
1411 // Test whether we need to force Unix paths.
1412 if(const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS"))
1414 if(!cmSystemTools::IsOff(force))
1416 cmSystemTools::SetForceUnixPaths(true);
1420 // Setup relative path top directories.
1421 this->RelativePathsConfigured = true;
1422 if(const char* relativePathTopSource =
1423 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE"))
1425 this->RelativePathTopSource = relativePathTopSource;
1427 if(const char* relativePathTopBinary =
1428 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY"))
1430 this->RelativePathTopBinary = relativePathTopBinary;
1433 else
1435 cmSystemTools::Error("Directory Information file not found");
1438 // create the file stream for the depends file
1439 std::string dir = targetDir;
1441 // Open the make depends file. This should be copy-if-different
1442 // because the make tool may try to reload it needlessly otherwise.
1443 std::string ruleFileNameFull = dir;
1444 ruleFileNameFull += "/depend.make";
1445 cmGeneratedFileStream ruleFileStream(ruleFileNameFull.c_str());
1446 ruleFileStream.SetCopyIfDifferent(true);
1447 if(!ruleFileStream)
1449 return false;
1452 // Open the cmake dependency tracking file. This should not be
1453 // copy-if-different because dependencies are re-scanned when it is
1454 // older than the DependInfo.cmake.
1455 std::string internalRuleFileNameFull = dir;
1456 internalRuleFileNameFull += "/depend.internal";
1457 cmGeneratedFileStream
1458 internalRuleFileStream(internalRuleFileNameFull.c_str());
1459 if(!internalRuleFileStream)
1461 return false;
1464 this->WriteDisclaimer(ruleFileStream);
1465 this->WriteDisclaimer(internalRuleFileStream);
1467 // for each language we need to scan, scan it
1468 const char *langStr = mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES");
1469 std::vector<std::string> langs;
1470 cmSystemTools::ExpandListArgument(langStr, langs);
1471 for (std::vector<std::string>::iterator li =
1472 langs.begin(); li != langs.end(); ++li)
1474 // construct the checker
1475 std::string lang = li->c_str();
1477 // Create the scanner for this language
1478 cmDepends *scanner = 0;
1479 if(lang == "C" || lang == "CXX" || lang == "RC")
1481 // TODO: Handle RC (resource files) dependencies correctly.
1482 scanner = new cmDependsC(this, targetDir, lang.c_str());
1484 #ifdef CMAKE_BUILD_WITH_CMAKE
1485 else if(lang == "Fortran")
1487 scanner = new cmDependsFortran(this);
1489 else if(lang == "Java")
1491 scanner = new cmDependsJava();
1493 #endif
1495 if (scanner)
1497 scanner->SetLocalGenerator(this);
1498 scanner->SetFileComparison
1499 (this->GlobalGenerator->GetCMakeInstance()->GetFileComparison());
1500 scanner->SetLanguage(lang.c_str());
1501 scanner->SetTargetDirectory(dir.c_str());
1502 scanner->Write(ruleFileStream, internalRuleFileStream);
1504 // free the scanner for this language
1505 delete scanner;
1509 return true;
1512 //----------------------------------------------------------------------------
1513 void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
1515 cmMakefile* mf = this->Makefile;
1517 // Get the string listing the multiple output pairs.
1518 const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
1519 if(!pairs_string)
1521 return;
1524 // Convert the string to a list and preserve empty entries.
1525 std::vector<std::string> pairs;
1526 cmSystemTools::ExpandListArgument(pairs_string, pairs, true);
1527 for(std::vector<std::string>::const_iterator i = pairs.begin();
1528 i != pairs.end() && (i+1) != pairs.end();)
1530 const std::string& depender = *i++;
1531 const std::string& dependee = *i++;
1533 // If the depender is missing then delete the dependee to make
1534 // sure both will be regenerated.
1535 if(cmSystemTools::FileExists(dependee.c_str()) &&
1536 !cmSystemTools::FileExists(depender.c_str()))
1538 if(verbose)
1540 cmOStringStream msg;
1541 msg << "Deleting primary custom command output \"" << dependee
1542 << "\" because another output \""
1543 << depender << "\" does not exist." << std::endl;
1544 cmSystemTools::Stdout(msg.str().c_str());
1546 cmSystemTools::RemoveFile(dependee.c_str());
1551 //----------------------------------------------------------------------------
1552 void cmLocalUnixMakefileGenerator3
1553 ::WriteLocalAllRules(std::ostream& ruleFileStream)
1555 this->WriteDisclaimer(ruleFileStream);
1557 // Write the main entry point target. This must be the VERY first
1558 // target so that make with no arguments will run it.
1560 // Just depend on the all target to drive the build.
1561 std::vector<std::string> depends;
1562 std::vector<std::string> no_commands;
1563 depends.push_back("all");
1565 // Write the rule.
1566 this->WriteMakeRule(ruleFileStream,
1567 "Default target executed when no arguments are "
1568 "given to make.",
1569 "default_target",
1570 depends,
1571 no_commands, true);
1574 this->WriteSpecialTargetsTop(ruleFileStream);
1576 // Include the progress variables for the target.
1577 // Write all global targets
1578 this->WriteDivider(ruleFileStream);
1579 ruleFileStream
1580 << "# Targets provided globally by CMake.\n"
1581 << "\n";
1582 cmTargets* targets = &(this->Makefile->GetTargets());
1583 cmTargets::iterator glIt;
1584 for ( glIt = targets->begin(); glIt != targets->end(); ++ glIt )
1586 if ( glIt->second.GetType() == cmTarget::GLOBAL_TARGET )
1588 std::string targetString = "Special rule for the target " + glIt->first;
1589 std::vector<std::string> commands;
1590 std::vector<std::string> depends;
1592 const char* text = glIt->second.GetProperty("EchoString");
1593 if ( !text )
1595 text = "Running external command ...";
1597 std::set<cmStdString>::const_iterator dit;
1598 for ( dit = glIt->second.GetUtilities().begin();
1599 dit != glIt->second.GetUtilities().end();
1600 ++ dit )
1602 depends.push_back(dit->c_str());
1604 this->AppendEcho(commands, text,
1605 cmLocalUnixMakefileGenerator3::EchoGlobal);
1607 // Global targets store their rules in pre- and post-build commands.
1608 this->AppendCustomDepends(depends,
1609 glIt->second.GetPreBuildCommands());
1610 this->AppendCustomDepends(depends,
1611 glIt->second.GetPostBuildCommands());
1612 this->AppendCustomCommands(commands,
1613 glIt->second.GetPreBuildCommands());
1614 this->AppendCustomCommands(commands,
1615 glIt->second.GetPostBuildCommands());
1616 std::string targetName = glIt->second.GetName();
1617 this->WriteMakeRule(ruleFileStream, targetString.c_str(),
1618 targetName.c_str(), depends, commands, true);
1620 // Provide a "/fast" version of the target.
1621 depends.clear();
1622 if((targetName == "install")
1623 || (targetName == "install_local")
1624 || (targetName == "install_strip"))
1626 // Provide a fast install target that does not depend on all
1627 // but has the same command.
1628 depends.push_back("preinstall/fast");
1630 else
1632 // Just forward to the real target so at least it will work.
1633 depends.push_back(targetName);
1634 commands.clear();
1636 targetName += "/fast";
1637 this->WriteMakeRule(ruleFileStream, targetString.c_str(),
1638 targetName.c_str(), depends, commands, true);
1642 std::vector<std::string> depends;
1643 std::vector<std::string> commands;
1645 // Write the all rule.
1646 std::string dir;
1647 std::string recursiveTarget = this->Makefile->GetStartOutputDirectory();
1648 recursiveTarget += "/all";
1650 depends.push_back("cmake_check_build_system");
1652 std::string progressDir = this->Makefile->GetHomeOutputDirectory();
1653 progressDir += cmake::GetCMakeFilesDirectory();
1655 cmOStringStream progCmd;
1656 progCmd <<
1657 "$(CMAKE_COMMAND) -E cmake_progress_start ";
1658 progCmd << this->Convert(progressDir.c_str(),
1659 cmLocalGenerator::FULL,
1660 cmLocalGenerator::SHELL);
1662 std::string progressFile = cmake::GetCMakeFilesDirectory();
1663 progressFile += "/progress.make";
1664 std::string progressFileNameFull =
1665 this->ConvertToFullPath(progressFile.c_str());
1666 progCmd << " " << this->Convert(progressFileNameFull.c_str(),
1667 cmLocalGenerator::FULL,
1668 cmLocalGenerator::SHELL);
1669 commands.push_back(progCmd.str());
1671 std::string mf2Dir = cmake::GetCMakeFilesDirectoryPostSlash();
1672 mf2Dir += "Makefile2";
1673 commands.push_back(this->GetRecursiveMakeCall(mf2Dir.c_str(),
1674 recursiveTarget.c_str()));
1675 this->CreateCDCommand(commands,
1676 this->Makefile->GetHomeOutputDirectory(),
1677 this->Makefile->GetStartOutputDirectory());
1679 cmOStringStream progCmd;
1680 progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
1681 progCmd << this->Convert(progressDir.c_str(),
1682 cmLocalGenerator::FULL,
1683 cmLocalGenerator::SHELL);
1684 progCmd << " 0";
1685 commands.push_back(progCmd.str());
1687 this->WriteMakeRule(ruleFileStream, "The main all target", "all",
1688 depends, commands, true);
1690 // Write the clean rule.
1691 recursiveTarget = this->Makefile->GetStartOutputDirectory();
1692 recursiveTarget += "/clean";
1693 commands.clear();
1694 depends.clear();
1695 commands.push_back(this->GetRecursiveMakeCall(mf2Dir.c_str(),
1696 recursiveTarget.c_str()));
1697 this->CreateCDCommand(commands,
1698 this->Makefile->GetHomeOutputDirectory(),
1699 this->Makefile->GetStartOutputDirectory());
1700 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
1701 depends, commands, true);
1702 commands.clear();
1703 depends.clear();
1704 depends.push_back("clean");
1705 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
1706 depends, commands, true);
1708 // Write the preinstall rule.
1709 recursiveTarget = this->Makefile->GetStartOutputDirectory();
1710 recursiveTarget += "/preinstall";
1711 commands.clear();
1712 depends.clear();
1713 const char* noall =
1714 this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
1715 if(!noall || cmSystemTools::IsOff(noall))
1717 // Drive the build before installing.
1718 depends.push_back("all");
1720 else
1722 // At least make sure the build system is up to date.
1723 depends.push_back("cmake_check_build_system");
1725 commands.push_back
1726 (this->GetRecursiveMakeCall(mf2Dir.c_str(), recursiveTarget.c_str()));
1727 this->CreateCDCommand(commands,
1728 this->Makefile->GetHomeOutputDirectory(),
1729 this->Makefile->GetStartOutputDirectory());
1730 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1731 "preinstall", depends, commands, true);
1732 depends.clear();
1733 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1734 "preinstall/fast", depends, commands, true);
1736 // write the depend rule, really a recompute depends rule
1737 depends.clear();
1738 commands.clear();
1739 std::string cmakefileName = cmake::GetCMakeFilesDirectoryPostSlash();
1740 cmakefileName += "Makefile.cmake";
1741 std::string runRule =
1742 "$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
1743 runRule += " --check-build-system ";
1744 runRule += this->Convert(cmakefileName.c_str(),cmLocalGenerator::NONE,
1745 cmLocalGenerator::SHELL);
1746 runRule += " 1";
1747 commands.push_back(runRule);
1748 this->CreateCDCommand(commands,
1749 this->Makefile->GetHomeOutputDirectory(),
1750 this->Makefile->GetStartOutputDirectory());
1751 this->WriteMakeRule(ruleFileStream, "clear depends",
1752 "depend",
1753 depends, commands, true);
1757 //----------------------------------------------------------------------------
1758 void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
1759 bool verbose)
1761 // Get the list of target files to check
1762 const char* infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
1763 if(!infoDef)
1765 return;
1767 std::vector<std::string> files;
1768 cmSystemTools::ExpandListArgument(infoDef, files);
1770 // Each depend information file corresponds to a target. Clear the
1771 // dependencies for that target.
1772 cmDepends clearer;
1773 clearer.SetVerbose(verbose);
1774 for(std::vector<std::string>::iterator l = files.begin();
1775 l != files.end(); ++l)
1777 std::string dir = cmSystemTools::GetFilenamePath(l->c_str());
1779 // Clear the implicit dependency makefile.
1780 std::string dependFile = dir + "/depend.make";
1781 clearer.Clear(dependFile.c_str());
1783 // Remove the internal dependency check file to force
1784 // regeneration.
1785 std::string internalDependFile = dir + "/depend.internal";
1786 cmSystemTools::RemoveFile(internalDependFile.c_str());
1791 void cmLocalUnixMakefileGenerator3
1792 ::WriteDependLanguageInfo(std::ostream& cmakefileStream, cmTarget &target)
1794 ImplicitDependLanguageMap const& implicitLangs =
1795 this->GetImplicitDepends(target);
1797 // list the languages
1798 cmakefileStream
1799 << "# The set of languages for which implicit dependencies are needed:\n";
1800 cmakefileStream
1801 << "SET(CMAKE_DEPENDS_LANGUAGES\n";
1802 for(ImplicitDependLanguageMap::const_iterator
1803 l = implicitLangs.begin(); l != implicitLangs.end(); ++l)
1805 cmakefileStream << " \"" << l->first.c_str() << "\"\n";
1807 cmakefileStream << " )\n";
1809 // now list the files for each language
1810 cmakefileStream
1811 << "# The set of files for implicit dependencies of each language:\n";
1812 for(ImplicitDependLanguageMap::const_iterator
1813 l = implicitLangs.begin(); l != implicitLangs.end(); ++l)
1815 cmakefileStream
1816 << "SET(CMAKE_DEPENDS_CHECK_" << l->first.c_str() << "\n";
1817 ImplicitDependFileMap const& implicitPairs = l->second;
1819 // for each file pair
1820 for(ImplicitDependFileMap::const_iterator pi = implicitPairs.begin();
1821 pi != implicitPairs.end(); ++pi)
1823 cmakefileStream << " \"" << pi->second << "\" ";
1824 cmakefileStream << "\"" << pi->first << "\"\n";
1826 cmakefileStream << " )\n";
1828 // Tell the dependency scanner what compiler is used.
1829 std::string cidVar = "CMAKE_";
1830 cidVar += l->first;
1831 cidVar += "_COMPILER_ID";
1832 const char* cid = this->Makefile->GetDefinition(cidVar.c_str());
1833 if(cid && *cid)
1835 cmakefileStream
1836 << "SET(CMAKE_" << l->first.c_str() << "_COMPILER_ID \""
1837 << cid << "\")\n";
1841 // Build a list of preprocessor definitions for the target.
1842 std::vector<std::string> defines;
1844 std::string defPropName = "COMPILE_DEFINITIONS_";
1845 defPropName += cmSystemTools::UpperCase(this->ConfigurationName);
1846 if(const char* ddefs = this->Makefile->GetProperty("COMPILE_DEFINITIONS"))
1848 cmSystemTools::ExpandListArgument(ddefs, defines);
1850 if(const char* cdefs = target.GetProperty("COMPILE_DEFINITIONS"))
1852 cmSystemTools::ExpandListArgument(cdefs, defines);
1854 if(const char* dcdefs = this->Makefile->GetProperty(defPropName.c_str()))
1856 cmSystemTools::ExpandListArgument(dcdefs, defines);
1858 if(const char* ccdefs = target.GetProperty(defPropName.c_str()))
1860 cmSystemTools::ExpandListArgument(ccdefs, defines);
1863 if(!defines.empty())
1865 cmakefileStream
1866 << "\n"
1867 << "# Preprocessor definitions for this target.\n"
1868 << "SET(CMAKE_TARGET_DEFINITIONS\n";
1869 for(std::vector<std::string>::const_iterator di = defines.begin();
1870 di != defines.end(); ++di)
1872 cmakefileStream
1873 << " " << this->EscapeForCMake(di->c_str()) << "\n";
1875 cmakefileStream
1876 << " )\n";
1879 // Store include transform rule properties. Write the directory
1880 // rules first because they may be overridden by later target rules.
1881 std::vector<std::string> transformRules;
1882 if(const char* xform =
1883 this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM"))
1885 cmSystemTools::ExpandListArgument(xform, transformRules);
1887 if(const char* xform =
1888 target.GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM"))
1890 cmSystemTools::ExpandListArgument(xform, transformRules);
1892 if(!transformRules.empty())
1894 cmakefileStream
1895 << "SET(CMAKE_INCLUDE_TRANSFORMS\n";
1896 for(std::vector<std::string>::const_iterator tri = transformRules.begin();
1897 tri != transformRules.end(); ++tri)
1899 cmakefileStream << " " << this->EscapeForCMake(tri->c_str()) << "\n";
1901 cmakefileStream
1902 << " )\n";
1906 //----------------------------------------------------------------------------
1907 std::string
1908 cmLocalUnixMakefileGenerator3
1909 ::GetObjectFileName(cmTarget& target,
1910 const cmSourceFile& source,
1911 std::string* nameWithoutTargetDir,
1912 bool* hasSourceExtension)
1914 // Make sure we never hit this old case.
1915 if(source.GetProperty("MACOSX_PACKAGE_LOCATION"))
1917 std::string msg = "MACOSX_PACKAGE_LOCATION set on source file: ";
1918 msg += source.GetFullPath();
1919 this->GetMakefile()->IssueMessage(cmake::INTERNAL_ERROR,
1920 msg.c_str());
1923 // Start with the target directory.
1924 std::string obj = this->GetTargetDirectory(target);
1925 obj += "/";
1927 // Get the object file name without the target directory.
1928 std::string::size_type dir_len = 0;
1929 dir_len += strlen(this->Makefile->GetCurrentOutputDirectory());
1930 dir_len += 1;
1931 dir_len += obj.size();
1932 std::string objectName =
1933 this->GetObjectFileNameWithoutTarget(source, dir_len,
1934 hasSourceExtension);
1935 if(nameWithoutTargetDir)
1937 *nameWithoutTargetDir = objectName;
1940 // Append the object name to the target directory.
1941 obj += objectName;
1942 return obj;
1945 //----------------------------------------------------------------------------
1946 void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
1949 << "# CMAKE generated file: DO NOT EDIT!\n"
1950 << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
1951 << " Generator, CMake Version "
1952 << cmVersion::GetMajorVersion() << "."
1953 << cmVersion::GetMinorVersion() << "\n\n";
1956 //----------------------------------------------------------------------------
1957 std::string
1958 cmLocalUnixMakefileGenerator3
1959 ::GetRecursiveMakeCall(const char *makefile, const char* tgt)
1961 // Call make on the given file.
1962 std::string cmd;
1963 cmd += "$(MAKE) -f ";
1964 cmd += this->Convert(makefile,NONE,SHELL);
1965 cmd += " ";
1967 // Passg down verbosity level.
1968 if(this->GetMakeSilentFlag().size())
1970 cmd += this->GetMakeSilentFlag();
1971 cmd += " ";
1974 // Most unix makes will pass the command line flags to make down to
1975 // sub-invoked makes via an environment variable. However, some
1976 // makes do not support that, so you have to pass the flags
1977 // explicitly.
1978 if(this->GetPassMakeflags())
1980 cmd += "-$(MAKEFLAGS) ";
1983 // Add the target.
1984 if (tgt && tgt[0] != '\0')
1986 // The make target is always relative to the top of the build tree.
1987 std::string tgt2 = this->Convert(tgt, HOME_OUTPUT);
1989 // The target may have been written with windows paths.
1990 cmSystemTools::ConvertToOutputSlashes(tgt2);
1992 // Escape one extra time if the make tool requires it.
1993 if(this->MakeCommandEscapeTargetTwice)
1995 tgt2 = this->EscapeForShell(tgt2.c_str(), true, false);
1998 // The target name is now a string that should be passed verbatim
1999 // on the command line.
2000 cmd += this->EscapeForShell(tgt2.c_str(), true, false);
2002 return cmd;
2005 //----------------------------------------------------------------------------
2006 void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
2009 << "#======================================"
2010 << "=======================================\n";
2013 //----------------------------------------------------------------------------
2014 void
2015 cmLocalUnixMakefileGenerator3
2016 ::WriteCMakeArgument(std::ostream& os, const char* s)
2018 // Write the given string to the stream with escaping to get it back
2019 // into CMake through the lexical scanner.
2020 os << "\"";
2021 for(const char* c = s; *c; ++c)
2023 if(*c == '\\')
2025 os << "\\\\";
2027 else if(*c == '"')
2029 os << "\\\"";
2031 else
2033 os << *c;
2036 os << "\"";
2039 //----------------------------------------------------------------------------
2040 std::string
2041 cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(const char* p)
2044 // Split the path into its components.
2045 std::vector<std::string> components;
2046 cmSystemTools::SplitPath(p, components);
2048 // Return an empty path if there are no components.
2049 if(components.empty())
2051 return "\"\"";
2054 // Choose a slash direction and fix root component.
2055 const char* slash = "/";
2056 #if defined(_WIN32) && !defined(__CYGWIN__)
2057 if(!cmSystemTools::GetForceUnixPaths())
2059 slash = "\\";
2060 for(std::string::iterator i = components[0].begin();
2061 i != components[0].end(); ++i)
2063 if(*i == '/')
2065 *i = '\\';
2069 #endif
2071 // Begin the quoted result with the root component.
2072 std::string result = "\"";
2073 result += components[0];
2075 // Now add the rest of the components separated by the proper slash
2076 // direction for this platform.
2077 bool first = true;
2078 for(unsigned int i=1; i < components.size(); ++i)
2080 // Only the last component can be empty to avoid double slashes.
2081 if(components[i].length() > 0 || (i == (components.size()-1)))
2083 if(!first)
2085 result += slash;
2087 result += components[i];
2088 first = false;
2092 // Close the quoted result.
2093 result += "\"";
2095 return result;
2098 //----------------------------------------------------------------------------
2099 std::string
2100 cmLocalUnixMakefileGenerator3
2101 ::GetTargetDirectory(cmTarget const& target) const
2103 std::string dir = cmake::GetCMakeFilesDirectoryPostSlash();
2104 dir += target.GetName();
2105 dir += ".dir";
2106 return dir;
2109 //----------------------------------------------------------------------------
2110 cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
2111 cmLocalUnixMakefileGenerator3::GetImplicitDepends(cmTarget const& tgt)
2113 return this->ImplicitDepends[tgt.GetName()];
2116 //----------------------------------------------------------------------------
2117 void
2118 cmLocalUnixMakefileGenerator3::AddImplicitDepends(cmTarget const& tgt,
2119 const char* lang,
2120 const char* obj,
2121 const char* src)
2123 this->ImplicitDepends[tgt.GetName()][lang][obj] = src;
2126 //----------------------------------------------------------------------------
2127 void cmLocalUnixMakefileGenerator3
2128 ::CreateCDCommand(std::vector<std::string>& commands, const char *tgtDir,
2129 const char *retDir)
2131 // do we need to cd?
2132 if (!strcmp(tgtDir,retDir))
2134 return;
2137 if(!this->UnixCD)
2139 // On Windows we must perform each step separately and then change
2140 // back because the shell keeps the working directory between
2141 // commands.
2142 std::string cmd = "cd ";
2143 cmd += this->ConvertToOutputForExisting(tgtDir);
2144 commands.insert(commands.begin(),cmd);
2146 // Change back to the starting directory. Any trailing slash must be
2147 // removed to avoid problems with Borland Make.
2148 std::string back = retDir;
2149 if(back.size() && back[back.size()-1] == '/')
2151 back = back.substr(0, back.size()-1);
2153 cmd = "cd ";
2154 cmd += this->ConvertToOutputForExisting(back.c_str());
2155 commands.push_back(cmd);
2157 else
2159 // On UNIX we must construct a single shell command to change
2160 // directory and build because make resets the directory between
2161 // each command.
2162 std::vector<std::string>::iterator i = commands.begin();
2163 for (; i != commands.end(); ++i)
2165 std::string cmd = "cd ";
2166 cmd += this->ConvertToOutputForExisting(tgtDir);
2167 cmd += " && ";
2168 cmd += *i;
2169 *i = cmd;
2175 void cmLocalUnixMakefileGenerator3
2176 ::GetTargetObjectFileDirectories(cmTarget* target,
2177 std::vector<std::string>& dirs)
2179 std::string dir = this->Makefile->GetCurrentOutputDirectory();
2180 dir += "/";
2181 dir += this->GetTargetDirectory(*target);
2182 dirs.push_back(dir);