Resync
[CMakeLuaTailorHgBridge.git] / CMakeLua / Source / cmLocalUnixMakefileGenerator3.cxx
blob38422648f1c931b26506ec63a9e90a8ddc37415b
1 /*=========================================================================
3 Program: CMake - Cross-Platform Makefile Generator
4 Module: $RCSfile: cmLocalUnixMakefileGenerator3.cxx,v $
5 Language: C++
6 Date: $Date: 2008-03-25 14:11:48 $
7 Version: $Revision: 1.245 $
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 << "# This makes gmake faster as it does not try to run implicit rules\n"
750 << "# on targets that never exist.\n"
751 << "SUFFIXES =\n"
752 << "%: %,v\n"
753 << "%: RCS/%,v\n"
754 << "%: RCS/%\n"
755 << "%: s.%\n"
756 << "%: %.w\n"
757 << "%.c: %.w %.ch\n"
758 << "%: %.tex\n"
759 << "%: SCCS/s.%\n\n";
761 // Add a fake suffix to keep HP happy. Must be max 32 chars for SGI make.
762 std::vector<std::string> depends;
763 depends.push_back(".hpux_make_needs_suffix_list");
764 this->WriteMakeRule(makefileStream, 0,
765 ".SUFFIXES", depends, no_commands, false);
767 cmGlobalUnixMakefileGenerator3* gg =
768 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
769 // Write special target to silence make output. This must be after
770 // the default target in case VERBOSE is set (which changes the
771 // name). The setting of CMAKE_VERBOSE_MAKEFILE to ON will cause a
772 // "VERBOSE=1" to be added as a make variable which will change the
773 // name of this special target. This gives a make-time choice to
774 // the user.
775 if((this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE"))
776 || (gg->GetForceVerboseMakefiles()))
778 makefileStream
779 << "# Produce verbose output by default.\n"
780 << "VERBOSE = 1\n"
781 << "\n";
783 if(this->SilentNoColon)
785 makefileStream << "$(VERBOSE).SILENT\n";
787 else
789 this->WriteMakeRule(makefileStream,
790 "Suppress display of executed commands.",
791 "$(VERBOSE).SILENT",
792 no_depends,
793 no_commands, false);
796 // Work-around for makes that drop rules that have no dependencies
797 // or commands.
798 std::string hack = gg->GetEmptyRuleHackDepends();
799 if(!hack.empty())
801 no_depends.push_back(hack);
803 std::string hack_cmd = gg->GetEmptyRuleHackCommand();
804 if(!hack_cmd.empty())
806 no_commands.push_back(hack_cmd);
809 // Special symbolic target that never exists to force dependers to
810 // run their rules.
811 this->WriteMakeRule
812 (makefileStream,
813 "A target that is always out of date.",
814 "cmake_force", no_depends, no_commands, true);
816 // Variables for reference by other rules.
817 this->WriteMakeVariables(makefileStream);
820 //----------------------------------------------------------------------------
821 void cmLocalUnixMakefileGenerator3
822 ::WriteSpecialTargetsBottom(std::ostream& makefileStream)
824 this->WriteDivider(makefileStream);
825 makefileStream
826 << "# Special targets to cleanup operation of make.\n"
827 << "\n";
829 // Write special "cmake_check_build_system" target to run cmake with
830 // the --check-build-system flag.
832 // Build command to run CMake to check if anything needs regenerating.
833 std::string cmakefileName = cmake::GetCMakeFilesDirectoryPostSlash();
834 cmakefileName += "Makefile.cmake";
835 std::string runRule =
836 "$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
837 runRule += " --check-build-system ";
838 runRule += this->Convert(cmakefileName.c_str(),NONE,SHELL);
839 runRule += " 0";
841 std::vector<std::string> no_depends;
842 std::vector<std::string> commands;
843 commands.push_back(runRule);
844 if(this->Parent)
846 this->CreateCDCommand(commands,
847 this->Makefile->GetHomeOutputDirectory(),
848 this->Makefile->GetStartOutputDirectory());
850 this->WriteMakeRule(makefileStream,
851 "Special rule to run CMake to check the build system "
852 "integrity.\n"
853 "No rule that depends on this can have "
854 "commands that come from listfiles\n"
855 "because they might be regenerated.",
856 "cmake_check_build_system",
857 no_depends,
858 commands, true);
864 //----------------------------------------------------------------------------
865 void
866 cmLocalUnixMakefileGenerator3
867 ::WriteConvenienceRule(std::ostream& ruleFileStream,
868 const char* realTarget,
869 const char* helpTarget)
871 // A rule is only needed if the names are different.
872 if(strcmp(realTarget, helpTarget) != 0)
874 // The helper target depends on the real target.
875 std::vector<std::string> depends;
876 depends.push_back(realTarget);
878 // There are no commands.
879 std::vector<std::string> no_commands;
881 // Write the rule.
882 this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
883 helpTarget, depends, no_commands, true);
888 //----------------------------------------------------------------------------
889 std::string
890 cmLocalUnixMakefileGenerator3
891 ::GetRelativeTargetDirectory(cmTarget const& target)
893 std::string dir = this->HomeRelativeOutputPath;
894 dir += this->GetTargetDirectory(target);
895 return this->Convert(dir.c_str(),NONE,UNCHANGED);
900 //----------------------------------------------------------------------------
901 void cmLocalUnixMakefileGenerator3::AppendFlags(std::string& flags,
902 const char* newFlags)
904 if(this->WatcomWMake && newFlags && *newFlags)
906 std::string newf = newFlags;
907 if(newf.find("\\\"") != newf.npos)
909 cmSystemTools::ReplaceString(newf, "\\\"", "\"");
910 this->cmLocalGenerator::AppendFlags(flags, newf.c_str());
911 return;
914 this->cmLocalGenerator::AppendFlags(flags, newFlags);
917 //----------------------------------------------------------------------------
918 void
919 cmLocalUnixMakefileGenerator3
920 ::AppendRuleDepend(std::vector<std::string>& depends,
921 const char* ruleFileName)
923 // Add a dependency on the rule file itself unless an option to skip
924 // it is specifically enabled by the user or project.
925 const char* nodep =
926 this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY");
927 if(!nodep || cmSystemTools::IsOff(nodep))
929 depends.push_back(ruleFileName);
933 //----------------------------------------------------------------------------
934 void
935 cmLocalUnixMakefileGenerator3
936 ::AppendCustomDepends(std::vector<std::string>& depends,
937 const std::vector<cmCustomCommand>& ccs)
939 for(std::vector<cmCustomCommand>::const_iterator i = ccs.begin();
940 i != ccs.end(); ++i)
942 this->AppendCustomDepend(depends, *i);
946 //----------------------------------------------------------------------------
947 void
948 cmLocalUnixMakefileGenerator3
949 ::AppendCustomDepend(std::vector<std::string>& depends,
950 const cmCustomCommand& cc)
952 for(std::vector<std::string>::const_iterator d = cc.GetDepends().begin();
953 d != cc.GetDepends().end(); ++d)
955 // Lookup the real name of the dependency in case it is a CMake target.
956 std::string dep = this->GetRealDependency
957 (d->c_str(), this->ConfigurationName.c_str());
958 depends.push_back(dep);
962 //----------------------------------------------------------------------------
963 void
964 cmLocalUnixMakefileGenerator3
965 ::AppendCustomCommands(std::vector<std::string>& commands,
966 const std::vector<cmCustomCommand>& ccs)
968 for(std::vector<cmCustomCommand>::const_iterator i = ccs.begin();
969 i != ccs.end(); ++i)
971 this->AppendCustomCommand(commands, *i, true);
975 //----------------------------------------------------------------------------
976 void
977 cmLocalUnixMakefileGenerator3
978 ::AppendCustomCommand(std::vector<std::string>& commands,
979 const cmCustomCommand& cc, bool echo_comment)
981 // Optionally create a command to display the custom command's
982 // comment text. This is used for pre-build, pre-link, and
983 // post-build command comments. Custom build step commands have
984 // their comments generated elsewhere.
985 if(echo_comment)
987 const char* comment = cc.GetComment();
988 if(comment && *comment)
990 this->AppendEcho(commands, comment,
991 cmLocalUnixMakefileGenerator3::EchoGenerate);
995 // if the command specified a working directory use it.
996 const char* dir = this->Makefile->GetStartOutputDirectory();
997 const char* workingDir = cc.GetWorkingDirectory();
998 if(workingDir)
1000 dir = workingDir;
1002 bool escapeOldStyle = cc.GetEscapeOldStyle();
1003 bool escapeAllowMakeVars = cc.GetEscapeAllowMakeVars();
1005 // Add each command line to the set of commands.
1006 std::vector<std::string> commands1;
1007 for(cmCustomCommandLines::const_iterator cl = cc.GetCommandLines().begin();
1008 cl != cc.GetCommandLines().end(); ++cl)
1010 // Build the command line in a single string.
1011 const cmCustomCommandLine& commandLine = *cl;
1012 std::string cmd = GetRealLocation(commandLine[0].c_str(),
1013 this->ConfigurationName.c_str());
1014 if (cmd.size())
1016 cmSystemTools::ReplaceString(cmd, "/./", "/");
1017 // Convert the command to a relative path only if the current
1018 // working directory will be the start-output directory.
1019 bool had_slash = cmd.find("/") != cmd.npos;
1020 if(!workingDir)
1022 cmd = this->Convert(cmd.c_str(),START_OUTPUT);
1024 bool has_slash = cmd.find("/") != cmd.npos;
1025 if(had_slash && !has_slash)
1027 // This command was specified as a path to a file in the
1028 // current directory. Add a leading "./" so it can run
1029 // without the current directory being in the search path.
1030 cmd = "./" + cmd;
1032 cmd = this->Convert(cmd.c_str(),NONE,SHELL);
1033 for(unsigned int j=1; j < commandLine.size(); ++j)
1035 cmd += " ";
1036 if(escapeOldStyle)
1038 cmd += this->EscapeForShellOldStyle(commandLine[j].c_str());
1040 else
1042 cmd += this->EscapeForShell(commandLine[j].c_str(),
1043 escapeAllowMakeVars);
1046 if(this->BorlandMakeCurlyHack)
1048 // Borland Make has a very strange bug. If the first curly
1049 // brace anywhere in the command string is a left curly, it
1050 // must be written {{} instead of just {. Otherwise some
1051 // curly braces are removed. The hack can be skipped if the
1052 // first curly brace is the last character.
1053 std::string::size_type lcurly = cmd.find("{");
1054 if(lcurly != cmd.npos && lcurly < (cmd.size()-1))
1056 std::string::size_type rcurly = cmd.find("}");
1057 if(rcurly == cmd.npos || rcurly > lcurly)
1059 // The first curly is a left curly. Use the hack.
1060 std::string hack_cmd = cmd.substr(0, lcurly);
1061 hack_cmd += "{{}";
1062 hack_cmd += cmd.substr(lcurly+1);
1063 cmd = hack_cmd;
1067 commands1.push_back(cmd);
1071 // Setup the proper working directory for the commands.
1072 this->CreateCDCommand(commands1, dir,
1073 this->Makefile->GetHomeOutputDirectory());
1075 // push back the custom commands
1076 commands.insert(commands.end(), commands1.begin(), commands1.end());
1079 //----------------------------------------------------------------------------
1080 void
1081 cmLocalUnixMakefileGenerator3
1082 ::AppendCleanCommand(std::vector<std::string>& commands,
1083 const std::vector<std::string>& files,
1084 cmTarget& target, const char* filename)
1086 if(!files.empty())
1088 std::string cleanfile = this->Makefile->GetCurrentOutputDirectory();
1089 cleanfile += "/";
1090 cleanfile += this->GetTargetDirectory(target);
1091 cleanfile += "/cmake_clean";
1092 if(filename)
1094 cleanfile += "_";
1095 cleanfile += filename;
1097 cleanfile += ".cmake";
1098 std::string cleanfilePath = this->Convert(cleanfile.c_str(), FULL);
1099 std::ofstream fout(cleanfilePath.c_str());
1100 if(!fout)
1102 cmSystemTools::Error("Could not create ", cleanfilePath.c_str());
1104 fout << "FILE(REMOVE_RECURSE\n";
1105 std::string remove = "$(CMAKE_COMMAND) -P ";
1106 remove += this->Convert(cleanfile.c_str(), START_OUTPUT, SHELL);
1107 for(std::vector<std::string>::const_iterator f = files.begin();
1108 f != files.end(); ++f)
1110 fout << "\"" << this->Convert(f->c_str(),START_OUTPUT,UNCHANGED)
1111 << "\"\n";
1113 fout << ")\n";
1114 commands.push_back(remove);
1116 // For the main clean rule add per-language cleaning.
1117 if(!filename)
1119 // Get the set of source languages in the target.
1120 std::set<cmStdString> languages;
1121 target.GetLanguages(languages);
1122 fout << "\n"
1123 << "# Per-language clean rules from dependency scanning.\n"
1124 << "FOREACH(lang";
1125 for(std::set<cmStdString>::const_iterator l = languages.begin();
1126 l != languages.end(); ++l)
1128 fout << " " << *l;
1130 fout << ")\n"
1131 << " INCLUDE(" << this->GetTargetDirectory(target)
1132 << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
1133 << "ENDFOREACH(lang)\n";
1138 //----------------------------------------------------------------------------
1139 void
1140 cmLocalUnixMakefileGenerator3::AppendEcho(std::vector<std::string>& commands,
1141 const char* text,
1142 EchoColor color)
1144 // Choose the color for the text.
1145 std::string color_name;
1146 #ifdef CMAKE_BUILD_WITH_CMAKE
1147 if(this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile)
1149 // See cmake::ExecuteEchoColor in cmake.cxx for these options.
1150 // This color set is readable on both black and white backgrounds.
1151 switch(color)
1153 case EchoNormal:
1154 break;
1155 case EchoDepend:
1156 color_name = "--magenta --bold ";
1157 break;
1158 case EchoBuild:
1159 color_name = "--green ";
1160 break;
1161 case EchoLink:
1162 color_name = "--red --bold ";
1163 break;
1164 case EchoGenerate:
1165 color_name = "--blue --bold ";
1166 break;
1167 case EchoGlobal:
1168 color_name = "--cyan ";
1169 break;
1172 #else
1173 (void)color;
1174 #endif
1176 // Echo one line at a time.
1177 std::string line;
1178 line.reserve(200);
1179 for(const char* c = text;; ++c)
1181 if(*c == '\n' || *c == '\0')
1183 // Avoid writing a blank last line on end-of-string.
1184 if(*c != '\0' || !line.empty())
1186 // Add a command to echo this line.
1187 std::string cmd;
1188 if(color_name.empty())
1190 // Use the native echo command.
1191 cmd = this->NativeEchoCommand;
1192 cmd += this->EscapeForShell(line.c_str(), false,
1193 this->NativeEchoWindows);
1195 else
1197 // Use cmake to echo the text in color.
1198 cmd = "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ";
1199 cmd += color_name;
1200 cmd += this->EscapeForShell(line.c_str());
1202 commands.push_back(cmd);
1205 // Reset the line to emtpy.
1206 line = "";
1208 // Terminate on end-of-string.
1209 if(*c == '\0')
1211 return;
1214 else if(*c != '\r')
1216 // Append this character to the current line.
1217 line += *c;
1222 //----------------------------------------------------------------------------
1223 std::string
1224 cmLocalUnixMakefileGenerator3
1225 ::CreateMakeVariable(const char* sin, const char* s2in)
1227 std::string s = sin;
1228 std::string s2 = s2in;
1229 std::string unmodified = s;
1230 unmodified += s2;
1231 // if there is no restriction on the length of make variables
1232 // and there are no "." charactors in the string, then return the
1233 // unmodified combination.
1234 if((!this->MakefileVariableSize && unmodified.find('.') == s.npos)
1235 && (!this->MakefileVariableSize && unmodified.find('-') == s.npos))
1237 return unmodified;
1240 // see if the variable has been defined before and return
1241 // the modified version of the variable
1242 std::map<cmStdString, cmStdString>::iterator i =
1243 this->MakeVariableMap.find(unmodified);
1244 if(i != this->MakeVariableMap.end())
1246 return i->second;
1248 // start with the unmodified variable
1249 std::string ret = unmodified;
1250 // if this there is no value for this->MakefileVariableSize then
1251 // the string must have bad characters in it
1252 if(!this->MakefileVariableSize)
1254 cmSystemTools::ReplaceString(ret, ".", "_");
1255 cmSystemTools::ReplaceString(ret, "-", "__");
1256 int ni = 0;
1257 char buffer[5];
1258 // make sure the _ version is not already used, if
1259 // it is used then add number to the end of the variable
1260 while(this->ShortMakeVariableMap.count(ret) && ni < 1000)
1262 ++ni;
1263 sprintf(buffer, "%04d", ni);
1264 ret = unmodified + buffer;
1266 this->ShortMakeVariableMap[ret] = "1";
1267 this->MakeVariableMap[unmodified] = ret;
1268 return ret;
1271 // if the string is greater the 32 chars it is an invalid vairable name
1272 // for borland make
1273 if(static_cast<int>(ret.size()) > this->MakefileVariableSize)
1275 int keep = this->MakefileVariableSize - 8;
1276 int size = keep + 3;
1277 std::string str1 = s;
1278 std::string str2 = s2;
1279 // we must shorten the combined string by 4 charactors
1280 // keep no more than 24 charactors from the second string
1281 if(static_cast<int>(str2.size()) > keep)
1283 str2 = str2.substr(0, keep);
1285 if(static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size)
1287 str1 = str1.substr(0, size - str2.size());
1289 char buffer[5];
1290 int ni = 0;
1291 sprintf(buffer, "%04d", ni);
1292 ret = str1 + str2 + buffer;
1293 while(this->ShortMakeVariableMap.count(ret) && ni < 1000)
1295 ++ni;
1296 sprintf(buffer, "%04d", ni);
1297 ret = str1 + str2 + buffer;
1299 if(ni == 1000)
1301 cmSystemTools::Error("Borland makefile variable length too long");
1302 return unmodified;
1304 // once an unused variable is found
1305 this->ShortMakeVariableMap[ret] = "1";
1307 // always make an entry into the unmodified to variable map
1308 this->MakeVariableMap[unmodified] = ret;
1309 return ret;
1312 //----------------------------------------------------------------------------
1313 bool cmLocalUnixMakefileGenerator3::UpdateDependencies(const char* tgtInfo,
1314 bool verbose,
1315 bool color)
1317 // read in the target info file
1318 if(!this->Makefile->ReadListFile(0, tgtInfo) ||
1319 cmSystemTools::GetErrorOccuredFlag())
1321 cmSystemTools::Error("Target DependInfo.cmake file not found");
1324 // Check if any multiple output pairs have a missing file.
1325 this->CheckMultipleOutputs(verbose);
1327 std::string dir = cmSystemTools::GetFilenamePath(tgtInfo);
1328 std::string internalDependFile = dir + "/depend.internal";
1329 std::string dependFile = dir + "/depend.make";
1331 // If the target DependInfo.cmake file has changed since the last
1332 // time dependencies were scanned then force rescanning. This may
1333 // happen when a new source file is added and CMake regenerates the
1334 // project but no other sources were touched.
1335 bool needRescan = false;
1336 cmFileTimeComparison* ftc =
1337 this->GlobalGenerator->GetCMakeInstance()->GetFileComparison();
1339 int result;
1340 if(!ftc->FileTimeCompare(internalDependFile.c_str(), tgtInfo, &result) ||
1341 result < 0)
1343 if(verbose)
1345 cmOStringStream msg;
1346 msg << "Dependee \"" << tgtInfo
1347 << "\" is newer than depender \""
1348 << internalDependFile << "\"." << std::endl;
1349 cmSystemTools::Stdout(msg.str().c_str());
1351 needRescan = true;
1355 // Check the implicit dependencies to see if they are up to date.
1356 // The build.make file may have explicit dependencies for the object
1357 // files but these will not affect the scanning process so they need
1358 // not be considered.
1359 cmDependsC checker;
1360 checker.SetVerbose(verbose);
1361 checker.SetFileComparison(ftc);
1362 if(needRescan ||
1363 !checker.Check(dependFile.c_str(), internalDependFile.c_str()))
1365 // The dependencies must be regenerated.
1366 std::string targetName = cmSystemTools::GetFilenameName(dir);
1367 targetName = targetName.substr(0, targetName.length()-4);
1368 std::string message = "Scanning dependencies of target ";
1369 message += targetName;
1370 #ifdef CMAKE_BUILD_WITH_CMAKE
1371 cmSystemTools::MakefileColorEcho(
1372 cmsysTerminal_Color_ForegroundMagenta |
1373 cmsysTerminal_Color_ForegroundBold,
1374 message.c_str(), true, color);
1375 #else
1376 fprintf(stdout, "%s\n", message.c_str());
1377 #endif
1379 return this->ScanDependencies(dir.c_str());
1381 else
1383 // The dependencies are already up-to-date.
1384 return true;
1388 //----------------------------------------------------------------------------
1389 bool
1390 cmLocalUnixMakefileGenerator3
1391 ::ScanDependencies(const char* targetDir)
1393 // Read the directory information file.
1394 cmMakefile* mf = this->Makefile;
1395 bool haveDirectoryInfo = false;
1396 std::string dirInfoFile = this->Makefile->GetStartOutputDirectory();
1397 dirInfoFile += cmake::GetCMakeFilesDirectory();
1398 dirInfoFile += "/CMakeDirectoryInformation.cmake";
1399 if(mf->ReadListFile(0, dirInfoFile.c_str()) &&
1400 !cmSystemTools::GetErrorOccuredFlag())
1402 haveDirectoryInfo = true;
1405 // Lookup useful directory information.
1406 if(haveDirectoryInfo)
1408 // Test whether we need to force Unix paths.
1409 if(const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS"))
1411 if(!cmSystemTools::IsOff(force))
1413 cmSystemTools::SetForceUnixPaths(true);
1417 // Setup relative path top directories.
1418 this->RelativePathsConfigured = true;
1419 if(const char* relativePathTopSource =
1420 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE"))
1422 this->RelativePathTopSource = relativePathTopSource;
1424 if(const char* relativePathTopBinary =
1425 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY"))
1427 this->RelativePathTopBinary = relativePathTopBinary;
1430 else
1432 cmSystemTools::Error("Directory Information file not found");
1435 // create the file stream for the depends file
1436 std::string dir = targetDir;
1438 // Open the rule file. This should be copy-if-different because the
1439 // rules may depend on this file itself.
1440 std::string ruleFileNameFull = dir;
1441 ruleFileNameFull += "/depend.make";
1442 cmGeneratedFileStream ruleFileStream(ruleFileNameFull.c_str());
1443 ruleFileStream.SetCopyIfDifferent(true);
1444 if(!ruleFileStream)
1446 return false;
1448 std::string internalRuleFileNameFull = dir;
1449 internalRuleFileNameFull += "/depend.internal";
1450 cmGeneratedFileStream
1451 internalRuleFileStream(internalRuleFileNameFull.c_str());
1452 internalRuleFileStream.SetCopyIfDifferent(true);
1453 if(!internalRuleFileStream)
1455 return false;
1458 this->WriteDisclaimer(ruleFileStream);
1459 this->WriteDisclaimer(internalRuleFileStream);
1461 // for each language we need to scan, scan it
1462 const char *langStr = mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES");
1463 std::vector<std::string> langs;
1464 cmSystemTools::ExpandListArgument(langStr, langs);
1465 for (std::vector<std::string>::iterator li =
1466 langs.begin(); li != langs.end(); ++li)
1468 // construct the checker
1469 std::string lang = li->c_str();
1471 // Get the set of include directories.
1472 std::vector<std::string> includes;
1473 if(haveDirectoryInfo)
1475 std::string includePathVar = "CMAKE_";
1476 includePathVar += lang;
1477 includePathVar += "_INCLUDE_PATH";
1478 if(const char* includePath = mf->GetDefinition(includePathVar.c_str()))
1480 cmSystemTools::ExpandListArgument(includePath, includes);
1484 // Get the include file regular expression.
1485 std::string includeRegexScan = "^.*$";
1486 std::string includeRegexComplain = "^$";
1487 if(haveDirectoryInfo)
1489 std::string scanRegexVar = "CMAKE_";
1490 scanRegexVar += lang;
1491 scanRegexVar += "_INCLUDE_REGEX_SCAN";
1492 if(const char* scanRegex = mf->GetDefinition(scanRegexVar.c_str()))
1494 includeRegexScan = scanRegex;
1496 std::string complainRegexVar = "CMAKE_";
1497 complainRegexVar += lang;
1498 complainRegexVar += "_INCLUDE_REGEX_COMPLAIN";
1499 if(const char* complainRegex =
1500 mf->GetDefinition(complainRegexVar.c_str()))
1502 includeRegexComplain = complainRegex;
1506 // Create the scanner for this language
1507 cmDepends *scanner = 0;
1508 if(lang == "C" || lang == "CXX" || lang == "RC")
1510 std::string includeCacheFileName = dir;
1511 includeCacheFileName += "/";
1512 includeCacheFileName += lang;
1513 includeCacheFileName += ".includecache";
1515 // TODO: Handle RC (resource files) dependencies correctly.
1516 scanner = new cmDependsC(includes,
1517 includeRegexScan.c_str(),
1518 includeRegexComplain.c_str(),
1519 includeCacheFileName);
1521 #ifdef CMAKE_BUILD_WITH_CMAKE
1522 else if(lang == "Fortran")
1524 std::vector<std::string> defines;
1525 if(const char* c_defines =
1526 mf->GetDefinition("CMAKE_TARGET_DEFINITIONS"))
1528 cmSystemTools::ExpandListArgument(c_defines, defines);
1531 scanner = new cmDependsFortran(includes, defines);
1533 else if(lang == "Java")
1535 scanner = new cmDependsJava();
1537 #endif
1539 if (scanner)
1541 scanner->SetLocalGenerator(this);
1542 scanner->SetFileComparison
1543 (this->GlobalGenerator->GetCMakeInstance()->GetFileComparison());
1544 scanner->SetLanguage(lang.c_str());
1545 scanner->SetTargetDirectory(dir.c_str());
1546 scanner->Write(ruleFileStream, internalRuleFileStream);
1548 // free the scanner for this language
1549 delete scanner;
1553 return true;
1556 //----------------------------------------------------------------------------
1557 void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
1559 cmMakefile* mf = this->Makefile;
1561 // Get the string listing the multiple output pairs.
1562 const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
1563 if(!pairs_string)
1565 return;
1568 // Convert the string to a list and preserve empty entries.
1569 std::vector<std::string> pairs;
1570 cmSystemTools::ExpandListArgument(pairs_string, pairs, true);
1571 for(std::vector<std::string>::const_iterator i = pairs.begin();
1572 i != pairs.end(); ++i)
1574 const std::string& depender = *i;
1575 if(++i != pairs.end())
1577 const std::string& dependee = *i;
1579 // If the depender is missing then delete the dependee to make
1580 // sure both will be regenerated.
1581 if(cmSystemTools::FileExists(dependee.c_str()) &&
1582 !cmSystemTools::FileExists(depender.c_str()))
1584 if(verbose)
1586 cmOStringStream msg;
1587 msg << "Deleting primary custom command output \"" << dependee
1588 << "\" because another output \""
1589 << depender << "\" does not exist." << std::endl;
1590 cmSystemTools::Stdout(msg.str().c_str());
1592 cmSystemTools::RemoveFile(dependee.c_str());
1598 //----------------------------------------------------------------------------
1599 void cmLocalUnixMakefileGenerator3
1600 ::WriteLocalAllRules(std::ostream& ruleFileStream)
1602 this->WriteDisclaimer(ruleFileStream);
1604 // Write the main entry point target. This must be the VERY first
1605 // target so that make with no arguments will run it.
1607 // Just depend on the all target to drive the build.
1608 std::vector<std::string> depends;
1609 std::vector<std::string> no_commands;
1610 depends.push_back("all");
1612 // Write the rule.
1613 this->WriteMakeRule(ruleFileStream,
1614 "Default target executed when no arguments are "
1615 "given to make.",
1616 "default_target",
1617 depends,
1618 no_commands, true);
1621 this->WriteSpecialTargetsTop(ruleFileStream);
1623 // Include the progress variables for the target.
1624 // Write all global targets
1625 this->WriteDivider(ruleFileStream);
1626 ruleFileStream
1627 << "# Targets provided globally by CMake.\n"
1628 << "\n";
1629 cmTargets* targets = &(this->Makefile->GetTargets());
1630 cmTargets::iterator glIt;
1631 for ( glIt = targets->begin(); glIt != targets->end(); ++ glIt )
1633 if ( glIt->second.GetType() == cmTarget::GLOBAL_TARGET )
1635 std::string targetString = "Special rule for the target " + glIt->first;
1636 std::vector<std::string> commands;
1637 std::vector<std::string> depends;
1639 const char* text = glIt->second.GetProperty("EchoString");
1640 if ( !text )
1642 text = "Running external command ...";
1644 std::set<cmStdString>::const_iterator dit;
1645 for ( dit = glIt->second.GetUtilities().begin();
1646 dit != glIt->second.GetUtilities().end();
1647 ++ dit )
1649 depends.push_back(dit->c_str());
1651 this->AppendEcho(commands, text,
1652 cmLocalUnixMakefileGenerator3::EchoGlobal);
1654 // Global targets store their rules in pre- and post-build commands.
1655 this->AppendCustomDepends(depends,
1656 glIt->second.GetPreBuildCommands());
1657 this->AppendCustomDepends(depends,
1658 glIt->second.GetPostBuildCommands());
1659 this->AppendCustomCommands(commands,
1660 glIt->second.GetPreBuildCommands());
1661 this->AppendCustomCommands(commands,
1662 glIt->second.GetPostBuildCommands());
1663 std::string targetName = glIt->second.GetName();
1664 this->WriteMakeRule(ruleFileStream, targetString.c_str(),
1665 targetName.c_str(), depends, commands, true);
1667 // Provide a "/fast" version of the target.
1668 depends.clear();
1669 if((targetName == "install")
1670 || (targetName == "install_local")
1671 || (targetName == "install_strip"))
1673 // Provide a fast install target that does not depend on all
1674 // but has the same command.
1675 depends.push_back("preinstall/fast");
1677 else
1679 // Just forward to the real target so at least it will work.
1680 depends.push_back(targetName);
1681 commands.clear();
1683 targetName += "/fast";
1684 this->WriteMakeRule(ruleFileStream, targetString.c_str(),
1685 targetName.c_str(), depends, commands, true);
1689 std::vector<std::string> depends;
1690 std::vector<std::string> commands;
1692 // Write the all rule.
1693 std::string dir;
1694 std::string recursiveTarget = this->Makefile->GetStartOutputDirectory();
1695 recursiveTarget += "/all";
1697 depends.push_back("cmake_check_build_system");
1699 std::string progressDir = this->Makefile->GetHomeOutputDirectory();
1700 progressDir += cmake::GetCMakeFilesDirectory();
1702 cmOStringStream progCmd;
1703 progCmd <<
1704 "$(CMAKE_COMMAND) -E cmake_progress_start ";
1705 progCmd << this->Convert(progressDir.c_str(),
1706 cmLocalGenerator::FULL,
1707 cmLocalGenerator::SHELL);
1709 std::string progressFile = cmake::GetCMakeFilesDirectory();
1710 progressFile += "/progress.make";
1711 std::string progressFileNameFull =
1712 this->ConvertToFullPath(progressFile.c_str());
1713 progCmd << " " << this->Convert(progressFileNameFull.c_str(),
1714 cmLocalGenerator::FULL,
1715 cmLocalGenerator::SHELL);
1716 commands.push_back(progCmd.str());
1718 std::string mf2Dir = cmake::GetCMakeFilesDirectoryPostSlash();
1719 mf2Dir += "Makefile2";
1720 commands.push_back(this->GetRecursiveMakeCall(mf2Dir.c_str(),
1721 recursiveTarget.c_str()));
1722 this->CreateCDCommand(commands,
1723 this->Makefile->GetHomeOutputDirectory(),
1724 this->Makefile->GetStartOutputDirectory());
1726 cmOStringStream progCmd;
1727 progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
1728 progCmd << this->Convert(progressDir.c_str(),
1729 cmLocalGenerator::FULL,
1730 cmLocalGenerator::SHELL);
1731 progCmd << " 0";
1732 commands.push_back(progCmd.str());
1734 this->WriteMakeRule(ruleFileStream, "The main all target", "all",
1735 depends, commands, true);
1737 // Write the clean rule.
1738 recursiveTarget = this->Makefile->GetStartOutputDirectory();
1739 recursiveTarget += "/clean";
1740 commands.clear();
1741 depends.clear();
1742 commands.push_back(this->GetRecursiveMakeCall(mf2Dir.c_str(),
1743 recursiveTarget.c_str()));
1744 this->CreateCDCommand(commands,
1745 this->Makefile->GetHomeOutputDirectory(),
1746 this->Makefile->GetStartOutputDirectory());
1747 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
1748 depends, commands, true);
1749 commands.clear();
1750 depends.clear();
1751 depends.push_back("clean");
1752 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
1753 depends, commands, true);
1755 // Write the preinstall rule.
1756 recursiveTarget = this->Makefile->GetStartOutputDirectory();
1757 recursiveTarget += "/preinstall";
1758 commands.clear();
1759 depends.clear();
1760 const char* noall =
1761 this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
1762 if(!noall || cmSystemTools::IsOff(noall))
1764 // Drive the build before installing.
1765 depends.push_back("all");
1767 else
1769 // At least make sure the build system is up to date.
1770 depends.push_back("cmake_check_build_system");
1772 commands.push_back
1773 (this->GetRecursiveMakeCall(mf2Dir.c_str(), recursiveTarget.c_str()));
1774 this->CreateCDCommand(commands,
1775 this->Makefile->GetHomeOutputDirectory(),
1776 this->Makefile->GetStartOutputDirectory());
1777 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1778 "preinstall", depends, commands, true);
1779 depends.clear();
1780 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1781 "preinstall/fast", depends, commands, true);
1783 // write the depend rule, really a recompute depends rule
1784 depends.clear();
1785 commands.clear();
1786 std::string cmakefileName = cmake::GetCMakeFilesDirectoryPostSlash();
1787 cmakefileName += "Makefile.cmake";
1788 std::string runRule =
1789 "$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
1790 runRule += " --check-build-system ";
1791 runRule += this->Convert(cmakefileName.c_str(),cmLocalGenerator::NONE,
1792 cmLocalGenerator::SHELL);
1793 runRule += " 1";
1794 commands.push_back(runRule);
1795 this->CreateCDCommand(commands,
1796 this->Makefile->GetHomeOutputDirectory(),
1797 this->Makefile->GetStartOutputDirectory());
1798 this->WriteMakeRule(ruleFileStream, "clear depends",
1799 "depend",
1800 depends, commands, true);
1804 //----------------------------------------------------------------------------
1805 void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
1806 bool verbose)
1808 // Get the list of target files to check
1809 const char* infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
1810 if(!infoDef)
1812 return;
1814 std::vector<std::string> files;
1815 cmSystemTools::ExpandListArgument(infoDef, files);
1817 // Each depend information file corresponds to a target. Clear the
1818 // dependencies for that target.
1819 cmDepends clearer;
1820 clearer.SetVerbose(verbose);
1821 for(std::vector<std::string>::iterator l = files.begin();
1822 l != files.end(); ++l)
1824 std::string dir = cmSystemTools::GetFilenamePath(l->c_str());
1826 // Clear the implicit dependency makefile.
1827 std::string dependFile = dir + "/depend.make";
1828 clearer.Clear(dependFile.c_str());
1830 // Remove the internal dependency check file to force
1831 // regeneration.
1832 std::string internalDependFile = dir + "/depend.internal";
1833 cmSystemTools::RemoveFile(internalDependFile.c_str());
1838 void cmLocalUnixMakefileGenerator3
1839 ::WriteDependLanguageInfo(std::ostream& cmakefileStream, cmTarget &target)
1841 ImplicitDependLanguageMap const& implicitLangs =
1842 this->GetImplicitDepends(target);
1844 // list the languages
1845 cmakefileStream
1846 << "# The set of languages for which implicit dependencies are needed:\n";
1847 cmakefileStream
1848 << "SET(CMAKE_DEPENDS_LANGUAGES\n";
1849 for(ImplicitDependLanguageMap::const_iterator
1850 l = implicitLangs.begin(); l != implicitLangs.end(); ++l)
1852 cmakefileStream << " \"" << l->first.c_str() << "\"\n";
1854 cmakefileStream << " )\n";
1856 // now list the files for each language
1857 cmakefileStream
1858 << "# The set of files for implicit dependencies of each language:\n";
1859 for(ImplicitDependLanguageMap::const_iterator
1860 l = implicitLangs.begin(); l != implicitLangs.end(); ++l)
1862 cmakefileStream
1863 << "SET(CMAKE_DEPENDS_CHECK_" << l->first.c_str() << "\n";
1864 ImplicitDependFileMap const& implicitPairs = l->second;
1866 // for each file pair
1867 for(ImplicitDependFileMap::const_iterator pi = implicitPairs.begin();
1868 pi != implicitPairs.end(); ++pi)
1870 cmakefileStream << " \"" << pi->second << "\" ";
1871 cmakefileStream << "\"" << pi->first << "\"\n";
1873 cmakefileStream << " )\n";
1875 // Tell the dependency scanner what compiler is used.
1876 std::string cidVar = "CMAKE_";
1877 cidVar += l->first;
1878 cidVar += "_COMPILER_ID";
1879 const char* cid = this->Makefile->GetDefinition(cidVar.c_str());
1880 if(cid && *cid)
1882 cmakefileStream
1883 << "SET(CMAKE_" << l->first.c_str() << "_COMPILER_ID \""
1884 << cid << "\")\n";
1888 // Build a list of preprocessor definitions for the target.
1889 std::vector<std::string> defines;
1891 std::string defPropName = "COMPILE_DEFINITIONS_";
1892 defPropName += cmSystemTools::UpperCase(this->ConfigurationName);
1893 if(const char* ddefs = this->Makefile->GetProperty("COMPILE_DEFINITIONS"))
1895 cmSystemTools::ExpandListArgument(ddefs, defines);
1897 if(const char* cdefs = target.GetProperty("COMPILE_DEFINITIONS"))
1899 cmSystemTools::ExpandListArgument(cdefs, defines);
1901 if(const char* dcdefs = this->Makefile->GetProperty(defPropName.c_str()))
1903 cmSystemTools::ExpandListArgument(dcdefs, defines);
1905 if(const char* ccdefs = target.GetProperty(defPropName.c_str()))
1907 cmSystemTools::ExpandListArgument(ccdefs, defines);
1910 if(!defines.empty())
1912 cmakefileStream
1913 << "\n"
1914 << "# Preprocessor definitions for this target.\n"
1915 << "SET(CMAKE_TARGET_DEFINITIONS\n";
1916 for(std::vector<std::string>::const_iterator di = defines.begin();
1917 di != defines.end(); ++di)
1919 cmakefileStream
1920 << " " << this->EscapeForCMake(di->c_str()) << "\n";
1922 cmakefileStream
1923 << " )\n";
1927 //----------------------------------------------------------------------------
1928 std::string
1929 cmLocalUnixMakefileGenerator3
1930 ::GetObjectFileName(cmTarget& target,
1931 const cmSourceFile& source,
1932 std::string* nameWithoutTargetDir,
1933 bool* hasSourceExtension)
1935 // Make sure we never hit this old case.
1936 if(source.GetProperty("MACOSX_PACKAGE_LOCATION"))
1938 std::string msg = "MACOSX_PACKAGE_LOCATION set on source file: ";
1939 msg += source.GetFullPath();
1940 this->GetMakefile()->IssueMessage(cmake::INTERNAL_ERROR,
1941 msg.c_str());
1944 // Start with the target directory.
1945 std::string obj = this->GetTargetDirectory(target);
1946 obj += "/";
1948 // Get the object file name without the target directory.
1949 std::string::size_type dir_len = 0;
1950 dir_len += strlen(this->Makefile->GetCurrentOutputDirectory());
1951 dir_len += 1;
1952 dir_len += obj.size();
1953 std::string objectName =
1954 this->GetObjectFileNameWithoutTarget(source, dir_len,
1955 hasSourceExtension);
1956 if(nameWithoutTargetDir)
1958 *nameWithoutTargetDir = objectName;
1961 // Append the object name to the target directory.
1962 obj += objectName;
1963 return obj;
1966 //----------------------------------------------------------------------------
1967 void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
1970 << "# CMAKE generated file: DO NOT EDIT!\n"
1971 << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
1972 << " Generator, CMake Version "
1973 << cmVersion::GetMajorVersion() << "."
1974 << cmVersion::GetMinorVersion() << "\n\n";
1977 //----------------------------------------------------------------------------
1978 std::string
1979 cmLocalUnixMakefileGenerator3
1980 ::GetRecursiveMakeCall(const char *makefile, const char* tgt)
1982 // Call make on the given file.
1983 std::string cmd;
1984 cmd += "$(MAKE) -f ";
1985 cmd += this->Convert(makefile,NONE,SHELL);
1986 cmd += " ";
1988 // Passg down verbosity level.
1989 if(this->GetMakeSilentFlag().size())
1991 cmd += this->GetMakeSilentFlag();
1992 cmd += " ";
1995 // Most unix makes will pass the command line flags to make down to
1996 // sub-invoked makes via an environment variable. However, some
1997 // makes do not support that, so you have to pass the flags
1998 // explicitly.
1999 if(this->GetPassMakeflags())
2001 cmd += "-$(MAKEFLAGS) ";
2004 // Add the target.
2005 if (tgt && tgt[0] != '\0')
2007 // The make target is always relative to the top of the build tree.
2008 std::string tgt2 = this->Convert(tgt, HOME_OUTPUT);
2010 // The target may have been written with windows paths.
2011 cmSystemTools::ConvertToOutputSlashes(tgt2);
2013 // Escape one extra time if the make tool requires it.
2014 if(this->MakeCommandEscapeTargetTwice)
2016 tgt2 = this->EscapeForShell(tgt2.c_str(), true, false);
2019 // The target name is now a string that should be passed verbatim
2020 // on the command line.
2021 cmd += this->EscapeForShell(tgt2.c_str(), true, false);
2023 return cmd;
2026 //----------------------------------------------------------------------------
2027 void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
2030 << "#======================================"
2031 << "=======================================\n";
2034 //----------------------------------------------------------------------------
2035 void
2036 cmLocalUnixMakefileGenerator3
2037 ::WriteCMakeArgument(std::ostream& os, const char* s)
2039 // Write the given string to the stream with escaping to get it back
2040 // into CMake through the lexical scanner.
2041 os << "\"";
2042 for(const char* c = s; *c; ++c)
2044 if(*c == '\\')
2046 os << "\\\\";
2048 else if(*c == '"')
2050 os << "\\\"";
2052 else
2054 os << *c;
2057 os << "\"";
2060 //----------------------------------------------------------------------------
2061 std::string
2062 cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(const char* p)
2065 // Split the path into its components.
2066 std::vector<std::string> components;
2067 cmSystemTools::SplitPath(p, components);
2069 // Return an empty path if there are no components.
2070 if(components.empty())
2072 return "\"\"";
2075 // Choose a slash direction and fix root component.
2076 const char* slash = "/";
2077 #if defined(_WIN32) && !defined(__CYGWIN__)
2078 if(!cmSystemTools::GetForceUnixPaths())
2080 slash = "\\";
2081 for(std::string::iterator i = components[0].begin();
2082 i != components[0].end(); ++i)
2084 if(*i == '/')
2086 *i = '\\';
2090 #endif
2092 // Begin the quoted result with the root component.
2093 std::string result = "\"";
2094 result += components[0];
2096 // Now add the rest of the components separated by the proper slash
2097 // direction for this platform.
2098 bool first = true;
2099 for(unsigned int i=1; i < components.size(); ++i)
2101 // Only the last component can be empty to avoid double slashes.
2102 if(components[i].length() > 0 || (i == (components.size()-1)))
2104 if(!first)
2106 result += slash;
2108 result += components[i];
2109 first = false;
2113 // Close the quoted result.
2114 result += "\"";
2116 return result;
2119 //----------------------------------------------------------------------------
2120 std::string
2121 cmLocalUnixMakefileGenerator3
2122 ::GetTargetDirectory(cmTarget const& target) const
2124 std::string dir = cmake::GetCMakeFilesDirectoryPostSlash();
2125 dir += target.GetName();
2126 dir += ".dir";
2127 return dir;
2130 //----------------------------------------------------------------------------
2131 cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
2132 cmLocalUnixMakefileGenerator3::GetImplicitDepends(cmTarget const& tgt)
2134 return this->ImplicitDepends[tgt.GetName()];
2137 //----------------------------------------------------------------------------
2138 void
2139 cmLocalUnixMakefileGenerator3::AddImplicitDepends(cmTarget const& tgt,
2140 const char* lang,
2141 const char* obj,
2142 const char* src)
2144 this->ImplicitDepends[tgt.GetName()][lang][obj] = src;
2147 //----------------------------------------------------------------------------
2148 void cmLocalUnixMakefileGenerator3
2149 ::CreateCDCommand(std::vector<std::string>& commands, const char *tgtDir,
2150 const char *retDir)
2152 // do we need to cd?
2153 if (!strcmp(tgtDir,retDir))
2155 return;
2158 if(!this->UnixCD)
2160 // On Windows we must perform each step separately and then change
2161 // back because the shell keeps the working directory between
2162 // commands.
2163 std::string cmd = "cd ";
2164 cmd += this->ConvertToOutputForExisting(tgtDir);
2165 commands.insert(commands.begin(),cmd);
2167 // Change back to the starting directory. Any trailing slash must be
2168 // removed to avoid problems with Borland Make.
2169 std::string back = retDir;
2170 if(back.size() && back[back.size()-1] == '/')
2172 back = back.substr(0, back.size()-1);
2174 cmd = "cd ";
2175 cmd += this->ConvertToOutputForExisting(back.c_str());
2176 commands.push_back(cmd);
2178 else
2180 // On UNIX we must construct a single shell command to change
2181 // directory and build because make resets the directory between
2182 // each command.
2183 std::vector<std::string>::iterator i = commands.begin();
2184 for (; i != commands.end(); ++i)
2186 std::string cmd = "cd ";
2187 cmd += this->ConvertToOutputForExisting(tgtDir);
2188 cmd += " && ";
2189 cmd += *i;
2190 *i = cmd;
2196 void cmLocalUnixMakefileGenerator3
2197 ::GetTargetObjectFileDirectories(cmTarget* target,
2198 std::vector<std::string>& dirs)
2200 std::string dir = this->Makefile->GetCurrentOutputDirectory();
2201 dir += "/";
2202 dir += this->GetTargetDirectory(*target);
2203 dirs.push_back(dir);