Clarify documentation for if.
[cmake.git] / Source / cmLocalUnixMakefileGenerator3.cxx
blobd8fe43e786ccbcb4631aec4a933b919c7fd825a4
1 /*=========================================================================
3 Program: CMake - Cross-Platform Makefile Generator
4 Module: $RCSfile: cmLocalUnixMakefileGenerator3.cxx,v $
5 Language: C++
6 Date: $Date: 2009-07-21 15:58:43 $
7 Version: $Revision: 1.268 $
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 <cmsys/auto_ptr.hxx>
40 #include <memory> // auto_ptr
41 #include <queue>
43 //----------------------------------------------------------------------------
44 // Helper function used below.
45 static std::string cmSplitExtension(std::string const& in, std::string& base)
47 std::string ext;
48 std::string::size_type dot_pos = in.rfind(".");
49 if(dot_pos != std::string::npos)
51 // Remove the extension first in case &base == &in.
52 ext = in.substr(dot_pos, std::string::npos);
53 base = in.substr(0, dot_pos);
55 else
57 base = in;
59 return ext;
62 //----------------------------------------------------------------------------
63 cmLocalUnixMakefileGenerator3::cmLocalUnixMakefileGenerator3()
65 this->SilentNoColon = false;
66 this->WindowsShell = false;
67 this->IncludeDirective = "include";
68 this->MakefileVariableSize = 0;
69 this->IgnoreLibPrefix = false;
70 this->PassMakeflags = false;
71 this->DefineWindowsNULL = false;
72 this->UnixCD = true;
73 this->ColorMakefile = false;
74 this->SkipPreprocessedSourceRules = false;
75 this->SkipAssemblySourceRules = false;
76 this->NativeEchoCommand = "@echo ";
77 this->NativeEchoWindows = true;
78 this->MakeCommandEscapeTargetTwice = false;
79 this->IsMakefileGenerator = true;
80 this->BorlandMakeCurlyHack = false;
83 //----------------------------------------------------------------------------
84 cmLocalUnixMakefileGenerator3::~cmLocalUnixMakefileGenerator3()
88 //----------------------------------------------------------------------------
89 void cmLocalUnixMakefileGenerator3::Configure()
91 // Compute the path to use when referencing the current output
92 // directory from the top output directory.
93 this->HomeRelativeOutputPath =
94 this->Convert(this->Makefile->GetStartOutputDirectory(), HOME_OUTPUT);
95 if(this->HomeRelativeOutputPath == ".")
97 this->HomeRelativeOutputPath = "";
99 if(!this->HomeRelativeOutputPath.empty())
101 this->HomeRelativeOutputPath += "/";
103 this->cmLocalGenerator::Configure();
106 //----------------------------------------------------------------------------
107 void cmLocalUnixMakefileGenerator3::Generate()
109 // Store the configuration name that will be generated.
110 if(const char* config = this->Makefile->GetDefinition("CMAKE_BUILD_TYPE"))
112 // Use the build type given by the user.
113 this->ConfigurationName = config;
115 else
117 // No configuration type given.
118 this->ConfigurationName = "";
121 // Record whether some options are enabled to avoid checking many
122 // times later.
123 if(!this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile())
125 this->ColorMakefile = this->Makefile->IsOn("CMAKE_COLOR_MAKEFILE");
127 this->SkipPreprocessedSourceRules =
128 this->Makefile->IsOn("CMAKE_SKIP_PREPROCESSED_SOURCE_RULES");
129 this->SkipAssemblySourceRules =
130 this->Makefile->IsOn("CMAKE_SKIP_ASSEMBLY_SOURCE_RULES");
132 // Generate the rule files for each target.
133 cmTargets& targets = this->Makefile->GetTargets();
134 cmGlobalUnixMakefileGenerator3* gg =
135 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
136 for(cmTargets::iterator t = targets.begin(); t != targets.end(); ++t)
138 cmsys::auto_ptr<cmMakefileTargetGenerator> tg(
139 cmMakefileTargetGenerator::New(&(t->second)));
140 if (tg.get())
142 tg->WriteRuleFiles();
143 gg->RecordTargetProgress(tg.get());
147 // write the local Makefile
148 this->WriteLocalMakefile();
150 // Write the cmake file with information for this directory.
151 this->WriteDirectoryInformationFile();
154 //----------------------------------------------------------------------------
155 void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
157 // generate the includes
158 std::string ruleFileName = "Makefile";
160 // Open the rule file. This should be copy-if-different because the
161 // rules may depend on this file itself.
162 std::string ruleFileNameFull = this->ConvertToFullPath(ruleFileName);
163 cmGeneratedFileStream ruleFileStream(ruleFileNameFull.c_str());
164 if(!ruleFileStream)
166 return;
168 // always write the top makefile
169 if (this->Parent)
171 ruleFileStream.SetCopyIfDifferent(true);
174 // write the all rules
175 this->WriteLocalAllRules(ruleFileStream);
177 // only write local targets unless at the top Keep track of targets already
178 // listed.
179 std::set<cmStdString> emittedTargets;
180 if (this->Parent)
182 // write our targets, and while doing it collect up the object
183 // file rules
184 this->WriteLocalMakefileTargets(ruleFileStream,emittedTargets);
186 else
188 cmGlobalUnixMakefileGenerator3 *gg =
189 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
190 gg->WriteConvenienceRules(ruleFileStream,emittedTargets);
193 bool do_preprocess_rules =
194 this->GetCreatePreprocessedSourceRules();
195 bool do_assembly_rules =
196 this->GetCreateAssemblySourceRules();
198 // now write out the object rules
199 // for each object file name
200 for (std::map<cmStdString, LocalObjectInfo>::iterator lo =
201 this->LocalObjectFiles.begin();
202 lo != this->LocalObjectFiles.end(); ++lo)
204 // Add a convenience rule for building the object file.
205 this->WriteObjectConvenienceRule(ruleFileStream,
206 "target to build an object file",
207 lo->first.c_str(), lo->second);
209 // Check whether preprocessing and assembly rules make sense.
210 // They make sense only for C and C++ sources.
211 bool lang_is_c_or_cxx = false;
212 for(std::vector<LocalObjectEntry>::const_iterator ei =
213 lo->second.begin(); ei != lo->second.end(); ++ei)
215 if(ei->Language == "C" || ei->Language == "CXX")
217 lang_is_c_or_cxx = true;
221 // Add convenience rules for preprocessed and assembly files.
222 if(lang_is_c_or_cxx && (do_preprocess_rules || do_assembly_rules))
224 std::string::size_type dot_pos = lo->first.rfind(".");
225 std::string base = lo->first.substr(0, dot_pos);
226 if(do_preprocess_rules)
228 this->WriteObjectConvenienceRule(
229 ruleFileStream, "target to preprocess a source file",
230 (base + ".i").c_str(), lo->second);
232 if(do_assembly_rules)
234 this->WriteObjectConvenienceRule(
235 ruleFileStream, "target to generate assembly for a file",
236 (base + ".s").c_str(), lo->second);
241 // add a help target as long as there isn;t a real target named help
242 if(emittedTargets.insert("help").second)
244 cmGlobalUnixMakefileGenerator3 *gg =
245 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
246 gg->WriteHelpRule(ruleFileStream,this);
249 this->WriteSpecialTargetsBottom(ruleFileStream);
252 //----------------------------------------------------------------------------
253 void
254 cmLocalUnixMakefileGenerator3
255 ::WriteObjectConvenienceRule(std::ostream& ruleFileStream,
256 const char* comment, const char* output,
257 LocalObjectInfo const& info)
259 // If the rule includes the source file extension then create a
260 // version that has the extension removed. The help should include
261 // only the version without source extension.
262 bool inHelp = true;
263 if(info.HasSourceExtension)
265 // Remove the last extension. This should be kept.
266 std::string outBase1 = output;
267 std::string outExt1 = cmSplitExtension(outBase1, outBase1);
269 // Now remove the source extension and put back the last
270 // extension.
271 std::string outNoExt;
272 cmSplitExtension(outBase1, outNoExt);
273 outNoExt += outExt1;
275 // Add a rule to drive the rule below.
276 std::vector<std::string> depends;
277 depends.push_back(output);
278 std::vector<std::string> no_commands;
279 this->WriteMakeRule(ruleFileStream, 0,
280 outNoExt.c_str(), depends, no_commands, true, true);
281 inHelp = false;
284 // Recursively make the rule for each target using the object file.
285 std::vector<std::string> commands;
286 for(std::vector<LocalObjectEntry>::const_iterator t = info.begin();
287 t != info.end(); ++t)
289 std::string tgtMakefileName =
290 this->GetRelativeTargetDirectory(*(t->Target));
291 std::string targetName = tgtMakefileName;
292 tgtMakefileName += "/build.make";
293 targetName += "/";
294 targetName += output;
295 commands.push_back(
296 this->GetRecursiveMakeCall(tgtMakefileName.c_str(), targetName.c_str())
299 this->CreateCDCommand(commands,
300 this->Makefile->GetHomeOutputDirectory(),
301 cmLocalGenerator::START_OUTPUT);
303 // Write the rule to the makefile.
304 std::vector<std::string> no_depends;
305 this->WriteMakeRule(ruleFileStream, comment,
306 output, no_depends, commands, true, inHelp);
309 //----------------------------------------------------------------------------
310 void cmLocalUnixMakefileGenerator3
311 ::WriteLocalMakefileTargets(std::ostream& ruleFileStream,
312 std::set<cmStdString> &emitted)
314 std::vector<std::string> depends;
315 std::vector<std::string> commands;
317 // for each target we just provide a rule to cd up to the top and do a make
318 // on the target
319 cmTargets& targets = this->Makefile->GetTargets();
320 std::string localName;
321 for(cmTargets::iterator t = targets.begin(); t != targets.end(); ++t)
323 if((t->second.GetType() == cmTarget::EXECUTABLE) ||
324 (t->second.GetType() == cmTarget::STATIC_LIBRARY) ||
325 (t->second.GetType() == cmTarget::SHARED_LIBRARY) ||
326 (t->second.GetType() == cmTarget::MODULE_LIBRARY) ||
327 (t->second.GetType() == cmTarget::UTILITY))
329 emitted.insert(t->second.GetName());
331 // for subdirs add a rule to build this specific target by name.
332 localName = this->GetRelativeTargetDirectory(t->second);
333 localName += "/rule";
334 commands.clear();
335 depends.clear();
337 // Build the target for this pass.
338 std::string makefile2 = cmake::GetCMakeFilesDirectoryPostSlash();
339 makefile2 += "Makefile2";
340 commands.push_back(this->GetRecursiveMakeCall
341 (makefile2.c_str(),localName.c_str()));
342 this->CreateCDCommand(commands,
343 this->Makefile->GetHomeOutputDirectory(),
344 cmLocalGenerator::START_OUTPUT);
345 this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
346 localName.c_str(), depends, commands, true);
348 // Add a target with the canonical name (no prefix, suffix or path).
349 if(localName != t->second.GetName())
351 commands.clear();
352 depends.push_back(localName);
353 this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
354 t->second.GetName(), depends, commands, true);
357 // Add a fast rule to build the target
358 std::string makefileName = this->GetRelativeTargetDirectory(t->second);
359 makefileName += "/build.make";
360 // make sure the makefile name is suitable for a makefile
361 std::string makeTargetName =
362 this->GetRelativeTargetDirectory(t->second);
363 makeTargetName += "/build";
364 localName = t->second.GetName();
365 localName += "/fast";
366 depends.clear();
367 commands.clear();
368 commands.push_back(this->GetRecursiveMakeCall
369 (makefileName.c_str(), makeTargetName.c_str()));
370 this->CreateCDCommand(commands,
371 this->Makefile->GetHomeOutputDirectory(),
372 cmLocalGenerator::START_OUTPUT);
373 this->WriteMakeRule(ruleFileStream, "fast build rule for target.",
374 localName.c_str(), depends, commands, true);
376 // Add a local name for the rule to relink the target before
377 // installation.
378 if(t->second.NeedRelinkBeforeInstall(this->ConfigurationName.c_str()))
380 makeTargetName = this->GetRelativeTargetDirectory(t->second);
381 makeTargetName += "/preinstall";
382 localName = t->second.GetName();
383 localName += "/preinstall";
384 depends.clear();
385 commands.clear();
386 commands.push_back(this->GetRecursiveMakeCall
387 (makefile2.c_str(), makeTargetName.c_str()));
388 this->CreateCDCommand(commands,
389 this->Makefile->GetHomeOutputDirectory(),
390 cmLocalGenerator::START_OUTPUT);
391 this->WriteMakeRule(ruleFileStream,
392 "Manual pre-install relink rule for target.",
393 localName.c_str(), depends, commands, true);
399 //----------------------------------------------------------------------------
400 void cmLocalUnixMakefileGenerator3::WriteDirectoryInformationFile()
402 std::string infoFileName = this->Makefile->GetStartOutputDirectory();
403 infoFileName += cmake::GetCMakeFilesDirectory();
404 infoFileName += "/CMakeDirectoryInformation.cmake";
406 // Open the output file.
407 cmGeneratedFileStream infoFileStream(infoFileName.c_str());
408 if(!infoFileStream)
410 return;
413 // Write the do not edit header.
414 this->WriteDisclaimer(infoFileStream);
416 // Setup relative path conversion tops.
417 infoFileStream
418 << "# Relative path conversion top directories.\n"
419 << "SET(CMAKE_RELATIVE_PATH_TOP_SOURCE \"" << this->RelativePathTopSource
420 << "\")\n"
421 << "SET(CMAKE_RELATIVE_PATH_TOP_BINARY \"" << this->RelativePathTopBinary
422 << "\")\n"
423 << "\n";
425 // Tell the dependency scanner to use unix paths if necessary.
426 if(cmSystemTools::GetForceUnixPaths())
428 infoFileStream
429 << "# Force unix paths in dependencies.\n"
430 << "SET(CMAKE_FORCE_UNIX_PATHS 1)\n"
431 << "\n";
434 // Store the include search path for this directory.
435 infoFileStream
436 << "# The C and CXX include file search paths:\n";
437 infoFileStream
438 << "SET(CMAKE_C_INCLUDE_PATH\n";
439 std::vector<std::string> includeDirs;
440 this->GetIncludeDirectories(includeDirs);
441 for(std::vector<std::string>::iterator i = includeDirs.begin();
442 i != includeDirs.end(); ++i)
444 infoFileStream
445 << " \"" << this->Convert(i->c_str(),HOME_OUTPUT).c_str() << "\"\n";
447 infoFileStream
448 << " )\n";
449 infoFileStream
450 << "SET(CMAKE_CXX_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH})\n";
451 infoFileStream
452 << "SET(CMAKE_Fortran_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH})\n";
454 // Store the include regular expressions for this directory.
455 infoFileStream
456 << "\n"
457 << "# The C and CXX include file regular expressions for "
458 << "this directory.\n";
459 infoFileStream
460 << "SET(CMAKE_C_INCLUDE_REGEX_SCAN ";
461 this->WriteCMakeArgument(infoFileStream,
462 this->Makefile->GetIncludeRegularExpression());
463 infoFileStream
464 << ")\n";
465 infoFileStream
466 << "SET(CMAKE_C_INCLUDE_REGEX_COMPLAIN ";
467 this->WriteCMakeArgument(infoFileStream,
468 this->Makefile->GetComplainRegularExpression());
469 infoFileStream
470 << ")\n";
471 infoFileStream
472 << "SET(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})\n";
473 infoFileStream
474 << "SET(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN "
475 "${CMAKE_C_INCLUDE_REGEX_COMPLAIN})\n";
478 //----------------------------------------------------------------------------
479 std::string
480 cmLocalUnixMakefileGenerator3
481 ::ConvertToFullPath(const std::string& localPath)
483 std::string dir = this->Makefile->GetStartOutputDirectory();
484 dir += "/";
485 dir += localPath;
486 return dir;
490 const std::string &cmLocalUnixMakefileGenerator3::GetHomeRelativeOutputPath()
492 return this->HomeRelativeOutputPath;
496 //----------------------------------------------------------------------------
497 void
498 cmLocalUnixMakefileGenerator3
499 ::WriteMakeRule(std::ostream& os,
500 const char* comment,
501 const char* target,
502 const std::vector<std::string>& depends,
503 const std::vector<std::string>& commands,
504 bool symbolic,
505 bool in_help)
507 // Make sure there is a target.
508 if(!target || !*target)
510 cmSystemTools::Error("No target for WriteMakeRule! called with comment: ",
511 comment);
512 return;
515 std::string replace;
517 // Write the comment describing the rule in the makefile.
518 if(comment)
520 replace = comment;
521 std::string::size_type lpos = 0;
522 std::string::size_type rpos;
523 while((rpos = replace.find('\n', lpos)) != std::string::npos)
525 os << "# " << replace.substr(lpos, rpos-lpos) << "\n";
526 lpos = rpos+1;
528 os << "# " << replace.substr(lpos) << "\n";
531 // Construct the left hand side of the rule.
532 replace = target;
533 std::string tgt = this->Convert(replace.c_str(),HOME_OUTPUT,MAKEFILE);
534 const char* space = "";
535 if(tgt.size() == 1)
537 // Add a space before the ":" to avoid drive letter confusion on
538 // Windows.
539 space = " ";
542 // Mark the rule as symbolic if requested.
543 if(symbolic)
545 if(const char* sym =
546 this->Makefile->GetDefinition("CMAKE_MAKE_SYMBOLIC_RULE"))
548 os << tgt.c_str() << space << ": " << sym << "\n";
552 // Write the rule.
553 if(depends.empty())
555 // No dependencies. The commands will always run.
556 os << tgt.c_str() << space << ":\n";
558 else
560 // Split dependencies into multiple rule lines. This allows for
561 // very long dependency lists even on older make implementations.
562 for(std::vector<std::string>::const_iterator dep = depends.begin();
563 dep != depends.end(); ++dep)
565 replace = *dep;
566 replace = this->Convert(replace.c_str(),HOME_OUTPUT,MAKEFILE);
567 os << tgt.c_str() << space << ": " << replace.c_str() << "\n";
571 // Write the list of commands.
572 for(std::vector<std::string>::const_iterator i = commands.begin();
573 i != commands.end(); ++i)
575 replace = *i;
576 os << "\t" << replace.c_str() << "\n";
578 if(symbolic && !this->WatcomWMake)
580 os << ".PHONY : " << tgt.c_str() << "\n";
582 os << "\n";
583 // Add the output to the local help if requested.
584 if(in_help)
586 this->LocalHelp.push_back(target);
590 //----------------------------------------------------------------------------
591 void
592 cmLocalUnixMakefileGenerator3
593 ::WriteMakeVariables(std::ostream& makefileStream)
595 this->WriteDivider(makefileStream);
596 makefileStream
597 << "# Set environment variables for the build.\n"
598 << "\n";
599 if(this->DefineWindowsNULL)
601 makefileStream
602 << "!IF \"$(OS)\" == \"Windows_NT\"\n"
603 << "NULL=\n"
604 << "!ELSE\n"
605 << "NULL=nul\n"
606 << "!ENDIF\n";
608 if(this->WindowsShell)
610 makefileStream
611 << "SHELL = cmd.exe\n"
612 << "\n";
614 else
616 #if !defined(__VMS)
617 makefileStream
618 << "# The shell in which to execute make rules.\n"
619 << "SHELL = /bin/sh\n"
620 << "\n";
621 #endif
624 std::string cmakecommand =
625 this->Makefile->GetRequiredDefinition("CMAKE_COMMAND");
626 makefileStream
627 << "# The CMake executable.\n"
628 << "CMAKE_COMMAND = "
629 << this->Convert(cmakecommand.c_str(), FULL, SHELL).c_str()
630 << "\n"
631 << "\n";
632 makefileStream
633 << "# The command to remove a file.\n"
634 << "RM = "
635 << this->Convert(cmakecommand.c_str(),FULL,SHELL).c_str()
636 << " -E remove -f\n"
637 << "\n";
639 if(const char* edit_cmd =
640 this->Makefile->GetDefinition("CMAKE_EDIT_COMMAND"))
642 makefileStream
643 << "# The program to use to edit the cache.\n"
644 << "CMAKE_EDIT_COMMAND = "
645 << this->Convert(edit_cmd,FULL,SHELL) << "\n"
646 << "\n";
649 makefileStream
650 << "# The top-level source directory on which CMake was run.\n"
651 << "CMAKE_SOURCE_DIR = "
652 << this->Convert(this->Makefile->GetHomeDirectory(), FULL, SHELL)
653 << "\n"
654 << "\n";
655 makefileStream
656 << "# The top-level build directory on which CMake was run.\n"
657 << "CMAKE_BINARY_DIR = "
658 << this->Convert(this->Makefile->GetHomeOutputDirectory(), FULL, SHELL)
659 << "\n"
660 << "\n";
663 //----------------------------------------------------------------------------
664 void
665 cmLocalUnixMakefileGenerator3
666 ::WriteSpecialTargetsTop(std::ostream& makefileStream)
668 this->WriteDivider(makefileStream);
669 makefileStream
670 << "# Special targets provided by cmake.\n"
671 << "\n";
673 std::vector<std::string> no_commands;
674 std::vector<std::string> no_depends;
676 // Special target to cleanup operation of make tool.
677 // This should be the first target except for the default_target in
678 // the interface Makefile.
679 this->WriteMakeRule(
680 makefileStream, "Disable implicit rules so canoncical targets will work.",
681 ".SUFFIXES", no_depends, no_commands, false);
683 if(!this->NMake && !this->WatcomWMake && !this->BorlandMakeCurlyHack)
685 // turn off RCS and SCCS automatic stuff from gmake
686 makefileStream
687 << "# Remove some rules from gmake that .SUFFIXES does not remove.\n"
688 << "SUFFIXES =\n\n";
690 // Add a fake suffix to keep HP happy. Must be max 32 chars for SGI make.
691 std::vector<std::string> depends;
692 depends.push_back(".hpux_make_needs_suffix_list");
693 this->WriteMakeRule(makefileStream, 0,
694 ".SUFFIXES", depends, no_commands, false);
696 cmGlobalUnixMakefileGenerator3* gg =
697 static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
698 // Write special target to silence make output. This must be after
699 // the default target in case VERBOSE is set (which changes the
700 // name). The setting of CMAKE_VERBOSE_MAKEFILE to ON will cause a
701 // "VERBOSE=1" to be added as a make variable which will change the
702 // name of this special target. This gives a make-time choice to
703 // the user.
704 if((this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE"))
705 || (gg->GetForceVerboseMakefiles()))
707 makefileStream
708 << "# Produce verbose output by default.\n"
709 << "VERBOSE = 1\n"
710 << "\n";
712 if(this->SilentNoColon)
714 makefileStream << "$(VERBOSE).SILENT\n";
716 else
718 this->WriteMakeRule(makefileStream,
719 "Suppress display of executed commands.",
720 "$(VERBOSE).SILENT",
721 no_depends,
722 no_commands, false);
725 // Work-around for makes that drop rules that have no dependencies
726 // or commands.
727 std::string hack = gg->GetEmptyRuleHackDepends();
728 if(!hack.empty())
730 no_depends.push_back(hack);
732 std::string hack_cmd = gg->GetEmptyRuleHackCommand();
733 if(!hack_cmd.empty())
735 no_commands.push_back(hack_cmd);
738 // Special symbolic target that never exists to force dependers to
739 // run their rules.
740 this->WriteMakeRule
741 (makefileStream,
742 "A target that is always out of date.",
743 "cmake_force", no_depends, no_commands, true);
745 // Variables for reference by other rules.
746 this->WriteMakeVariables(makefileStream);
749 //----------------------------------------------------------------------------
750 void cmLocalUnixMakefileGenerator3
751 ::WriteSpecialTargetsBottom(std::ostream& makefileStream)
753 this->WriteDivider(makefileStream);
754 makefileStream
755 << "# Special targets to cleanup operation of make.\n"
756 << "\n";
758 // Write special "cmake_check_build_system" target to run cmake with
759 // the --check-build-system flag.
761 // Build command to run CMake to check if anything needs regenerating.
762 std::string cmakefileName = cmake::GetCMakeFilesDirectoryPostSlash();
763 cmakefileName += "Makefile.cmake";
764 std::string runRule =
765 "$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
766 runRule += " --check-build-system ";
767 runRule += this->Convert(cmakefileName.c_str(),NONE,SHELL);
768 runRule += " 0";
770 std::vector<std::string> no_depends;
771 std::vector<std::string> commands;
772 commands.push_back(runRule);
773 if(this->Parent)
775 this->CreateCDCommand(commands,
776 this->Makefile->GetHomeOutputDirectory(),
777 cmLocalGenerator::START_OUTPUT);
779 this->WriteMakeRule(makefileStream,
780 "Special rule to run CMake to check the build system "
781 "integrity.\n"
782 "No rule that depends on this can have "
783 "commands that come from listfiles\n"
784 "because they might be regenerated.",
785 "cmake_check_build_system",
786 no_depends,
787 commands, true);
793 //----------------------------------------------------------------------------
794 void
795 cmLocalUnixMakefileGenerator3
796 ::WriteConvenienceRule(std::ostream& ruleFileStream,
797 const char* realTarget,
798 const char* helpTarget)
800 // A rule is only needed if the names are different.
801 if(strcmp(realTarget, helpTarget) != 0)
803 // The helper target depends on the real target.
804 std::vector<std::string> depends;
805 depends.push_back(realTarget);
807 // There are no commands.
808 std::vector<std::string> no_commands;
810 // Write the rule.
811 this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
812 helpTarget, depends, no_commands, true);
817 //----------------------------------------------------------------------------
818 std::string
819 cmLocalUnixMakefileGenerator3
820 ::GetRelativeTargetDirectory(cmTarget const& target)
822 std::string dir = this->HomeRelativeOutputPath;
823 dir += this->GetTargetDirectory(target);
824 return this->Convert(dir.c_str(),NONE,UNCHANGED);
829 //----------------------------------------------------------------------------
830 void cmLocalUnixMakefileGenerator3::AppendFlags(std::string& flags,
831 const char* newFlags)
833 if(this->WatcomWMake && newFlags && *newFlags)
835 std::string newf = newFlags;
836 if(newf.find("\\\"") != newf.npos)
838 cmSystemTools::ReplaceString(newf, "\\\"", "\"");
839 this->cmLocalGenerator::AppendFlags(flags, newf.c_str());
840 return;
843 this->cmLocalGenerator::AppendFlags(flags, newFlags);
846 //----------------------------------------------------------------------------
847 void
848 cmLocalUnixMakefileGenerator3
849 ::AppendRuleDepend(std::vector<std::string>& depends,
850 const char* ruleFileName)
852 // Add a dependency on the rule file itself unless an option to skip
853 // it is specifically enabled by the user or project.
854 const char* nodep =
855 this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY");
856 if(!nodep || cmSystemTools::IsOff(nodep))
858 depends.push_back(ruleFileName);
862 //----------------------------------------------------------------------------
863 void
864 cmLocalUnixMakefileGenerator3
865 ::AppendCustomDepends(std::vector<std::string>& depends,
866 const std::vector<cmCustomCommand>& ccs)
868 for(std::vector<cmCustomCommand>::const_iterator i = ccs.begin();
869 i != ccs.end(); ++i)
871 this->AppendCustomDepend(depends, *i);
875 //----------------------------------------------------------------------------
876 void
877 cmLocalUnixMakefileGenerator3
878 ::AppendCustomDepend(std::vector<std::string>& depends,
879 const cmCustomCommand& cc)
881 for(std::vector<std::string>::const_iterator d = cc.GetDepends().begin();
882 d != cc.GetDepends().end(); ++d)
884 // Lookup the real name of the dependency in case it is a CMake target.
885 std::string dep = this->GetRealDependency
886 (d->c_str(), this->ConfigurationName.c_str());
887 depends.push_back(dep);
891 //----------------------------------------------------------------------------
892 void
893 cmLocalUnixMakefileGenerator3
894 ::AppendCustomCommands(std::vector<std::string>& commands,
895 const std::vector<cmCustomCommand>& ccs,
896 cmTarget* target,
897 cmLocalGenerator::RelativeRoot relative)
899 for(std::vector<cmCustomCommand>::const_iterator i = ccs.begin();
900 i != ccs.end(); ++i)
902 this->AppendCustomCommand(commands, *i, target, true, relative);
906 //----------------------------------------------------------------------------
907 void
908 cmLocalUnixMakefileGenerator3
909 ::AppendCustomCommand(std::vector<std::string>& commands,
910 const cmCustomCommand& cc,
911 cmTarget* target,
912 bool echo_comment,
913 cmLocalGenerator::RelativeRoot relative,
914 std::ostream* content)
916 // Optionally create a command to display the custom command's
917 // comment text. This is used for pre-build, pre-link, and
918 // post-build command comments. Custom build step commands have
919 // their comments generated elsewhere.
920 if(echo_comment)
922 const char* comment = cc.GetComment();
923 if(comment && *comment)
925 this->AppendEcho(commands, comment,
926 cmLocalUnixMakefileGenerator3::EchoGenerate);
930 // if the command specified a working directory use it.
931 const char* dir = this->Makefile->GetStartOutputDirectory();
932 const char* workingDir = cc.GetWorkingDirectory();
933 if(workingDir)
935 dir = workingDir;
937 if(content)
939 *content << dir;
941 bool escapeOldStyle = cc.GetEscapeOldStyle();
942 bool escapeAllowMakeVars = cc.GetEscapeAllowMakeVars();
944 // Add each command line to the set of commands.
945 std::vector<std::string> commands1;
946 for(cmCustomCommandLines::const_iterator cl = cc.GetCommandLines().begin();
947 cl != cc.GetCommandLines().end(); ++cl)
949 // Build the command line in a single string.
950 const cmCustomCommandLine& commandLine = *cl;
951 std::string cmd = GetRealLocation(commandLine[0].c_str(),
952 this->ConfigurationName.c_str());
953 if (cmd.size())
955 cmSystemTools::ReplaceString(cmd, "/./", "/");
956 // Convert the command to a relative path only if the current
957 // working directory will be the start-output directory.
958 bool had_slash = cmd.find("/") != cmd.npos;
959 if(!workingDir)
961 cmd = this->Convert(cmd.c_str(),START_OUTPUT);
963 bool has_slash = cmd.find("/") != cmd.npos;
964 if(had_slash && !has_slash)
966 // This command was specified as a path to a file in the
967 // current directory. Add a leading "./" so it can run
968 // without the current directory being in the search path.
969 cmd = "./" + cmd;
971 if(this->WatcomWMake &&
972 cmSystemTools::FileIsFullPath(cmd.c_str()) &&
973 cmd.find(" ") != cmd.npos)
975 // On Watcom WMake use the windows short path for the command
976 // name. This is needed to avoid funny quoting problems on
977 // lines with shell redirection operators.
978 std::string scmd;
979 if(cmSystemTools::GetShortPath(cmd.c_str(), scmd))
981 cmd = scmd;
984 std::string launcher =
985 this->MakeLauncher(cc, target, workingDir? NONE : START_OUTPUT);
986 cmd = launcher + this->Convert(cmd.c_str(),NONE,SHELL);
987 for(unsigned int j=1; j < commandLine.size(); ++j)
989 cmd += " ";
990 if(escapeOldStyle)
992 cmd += this->EscapeForShellOldStyle(commandLine[j].c_str());
994 else
996 cmd += this->EscapeForShell(commandLine[j].c_str(),
997 escapeAllowMakeVars);
1000 if(content)
1002 // Rule content does not include the launcher.
1003 *content << (cmd.c_str()+launcher.size());
1005 if(this->BorlandMakeCurlyHack)
1007 // Borland Make has a very strange bug. If the first curly
1008 // brace anywhere in the command string is a left curly, it
1009 // must be written {{} instead of just {. Otherwise some
1010 // curly braces are removed. The hack can be skipped if the
1011 // first curly brace is the last character.
1012 std::string::size_type lcurly = cmd.find("{");
1013 if(lcurly != cmd.npos && lcurly < (cmd.size()-1))
1015 std::string::size_type rcurly = cmd.find("}");
1016 if(rcurly == cmd.npos || rcurly > lcurly)
1018 // The first curly is a left curly. Use the hack.
1019 std::string hack_cmd = cmd.substr(0, lcurly);
1020 hack_cmd += "{{}";
1021 hack_cmd += cmd.substr(lcurly+1);
1022 cmd = hack_cmd;
1026 commands1.push_back(cmd);
1030 // Setup the proper working directory for the commands.
1031 this->CreateCDCommand(commands1, dir, relative);
1033 // push back the custom commands
1034 commands.insert(commands.end(), commands1.begin(), commands1.end());
1037 //----------------------------------------------------------------------------
1038 std::string
1039 cmLocalUnixMakefileGenerator3::MakeLauncher(const cmCustomCommand& cc,
1040 cmTarget* target,
1041 RelativeRoot relative)
1043 // Short-circuit if there is no launcher.
1044 const char* prop = "RULE_LAUNCH_CUSTOM";
1045 const char* val = this->GetRuleLauncher(target, prop);
1046 if(!(val && *val))
1048 return "";
1051 // Expand rules in the empty string. It may insert the launcher and
1052 // perform replacements.
1053 RuleVariables vars;
1054 vars.RuleLauncher = prop;
1055 vars.CMTarget = target;
1056 std::string output;
1057 const std::vector<std::string>& outputs = cc.GetOutputs();
1058 if(!outputs.empty())
1060 output = this->Convert(outputs[0].c_str(), relative, SHELL);
1062 vars.Output = output.c_str();
1064 std::string launcher;
1065 this->ExpandRuleVariables(launcher, vars);
1066 if(!launcher.empty())
1068 launcher += " ";
1070 return launcher;
1073 //----------------------------------------------------------------------------
1074 void
1075 cmLocalUnixMakefileGenerator3
1076 ::AppendCleanCommand(std::vector<std::string>& commands,
1077 const std::vector<std::string>& files,
1078 cmTarget& target, const char* filename)
1080 if(!files.empty())
1082 std::string cleanfile = this->Makefile->GetCurrentOutputDirectory();
1083 cleanfile += "/";
1084 cleanfile += this->GetTargetDirectory(target);
1085 cleanfile += "/cmake_clean";
1086 if(filename)
1088 cleanfile += "_";
1089 cleanfile += filename;
1091 cleanfile += ".cmake";
1092 std::string cleanfilePath = this->Convert(cleanfile.c_str(), FULL);
1093 std::ofstream fout(cleanfilePath.c_str());
1094 if(!fout)
1096 cmSystemTools::Error("Could not create ", cleanfilePath.c_str());
1098 fout << "FILE(REMOVE_RECURSE\n";
1099 std::string remove = "$(CMAKE_COMMAND) -P ";
1100 remove += this->Convert(cleanfile.c_str(), START_OUTPUT, SHELL);
1101 for(std::vector<std::string>::const_iterator f = files.begin();
1102 f != files.end(); ++f)
1104 std::string fc = this->Convert(f->c_str(),START_OUTPUT,UNCHANGED);
1105 fout << " " << this->EscapeForCMake(fc.c_str()) << "\n";
1107 fout << ")\n";
1108 commands.push_back(remove);
1110 // For the main clean rule add per-language cleaning.
1111 if(!filename)
1113 // Get the set of source languages in the target.
1114 std::set<cmStdString> languages;
1115 target.GetLanguages(languages);
1116 fout << "\n"
1117 << "# Per-language clean rules from dependency scanning.\n"
1118 << "FOREACH(lang";
1119 for(std::set<cmStdString>::const_iterator l = languages.begin();
1120 l != languages.end(); ++l)
1122 fout << " " << *l;
1124 fout << ")\n"
1125 << " INCLUDE(" << this->GetTargetDirectory(target)
1126 << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
1127 << "ENDFOREACH(lang)\n";
1132 //----------------------------------------------------------------------------
1133 void
1134 cmLocalUnixMakefileGenerator3::AppendEcho(std::vector<std::string>& commands,
1135 const char* text,
1136 EchoColor color)
1138 // Choose the color for the text.
1139 std::string color_name;
1140 #ifdef CMAKE_BUILD_WITH_CMAKE
1141 if(this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile)
1143 // See cmake::ExecuteEchoColor in cmake.cxx for these options.
1144 // This color set is readable on both black and white backgrounds.
1145 switch(color)
1147 case EchoNormal:
1148 break;
1149 case EchoDepend:
1150 color_name = "--magenta --bold ";
1151 break;
1152 case EchoBuild:
1153 color_name = "--green ";
1154 break;
1155 case EchoLink:
1156 color_name = "--red --bold ";
1157 break;
1158 case EchoGenerate:
1159 color_name = "--blue --bold ";
1160 break;
1161 case EchoGlobal:
1162 color_name = "--cyan ";
1163 break;
1166 #else
1167 (void)color;
1168 #endif
1170 // Echo one line at a time.
1171 std::string line;
1172 line.reserve(200);
1173 for(const char* c = text;; ++c)
1175 if(*c == '\n' || *c == '\0')
1177 // Avoid writing a blank last line on end-of-string.
1178 if(*c != '\0' || !line.empty())
1180 // Add a command to echo this line.
1181 std::string cmd;
1182 if(color_name.empty())
1184 // Use the native echo command.
1185 cmd = this->NativeEchoCommand;
1186 cmd += this->EscapeForShell(line.c_str(), false,
1187 this->NativeEchoWindows);
1189 else
1191 // Use cmake to echo the text in color.
1192 cmd = "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ";
1193 cmd += color_name;
1194 cmd += this->EscapeForShell(line.c_str());
1196 commands.push_back(cmd);
1199 // Reset the line to emtpy.
1200 line = "";
1202 // Terminate on end-of-string.
1203 if(*c == '\0')
1205 return;
1208 else if(*c != '\r')
1210 // Append this character to the current line.
1211 line += *c;
1216 //----------------------------------------------------------------------------
1217 std::string
1218 cmLocalUnixMakefileGenerator3
1219 ::CreateMakeVariable(const char* sin, const char* s2in)
1221 std::string s = sin;
1222 std::string s2 = s2in;
1223 std::string unmodified = s;
1224 unmodified += s2;
1225 // if there is no restriction on the length of make variables
1226 // and there are no "." charactors in the string, then return the
1227 // unmodified combination.
1228 if((!this->MakefileVariableSize && unmodified.find('.') == s.npos)
1229 && (!this->MakefileVariableSize && unmodified.find('-') == s.npos))
1231 return unmodified;
1234 // see if the variable has been defined before and return
1235 // the modified version of the variable
1236 std::map<cmStdString, cmStdString>::iterator i =
1237 this->MakeVariableMap.find(unmodified);
1238 if(i != this->MakeVariableMap.end())
1240 return i->second;
1242 // start with the unmodified variable
1243 std::string ret = unmodified;
1244 // if this there is no value for this->MakefileVariableSize then
1245 // the string must have bad characters in it
1246 if(!this->MakefileVariableSize)
1248 cmSystemTools::ReplaceString(ret, ".", "_");
1249 cmSystemTools::ReplaceString(ret, "-", "__");
1250 int ni = 0;
1251 char buffer[5];
1252 // make sure the _ version is not already used, if
1253 // it is used then add number to the end of the variable
1254 while(this->ShortMakeVariableMap.count(ret) && ni < 1000)
1256 ++ni;
1257 sprintf(buffer, "%04d", ni);
1258 ret = unmodified + buffer;
1260 this->ShortMakeVariableMap[ret] = "1";
1261 this->MakeVariableMap[unmodified] = ret;
1262 return ret;
1265 // if the string is greater the 32 chars it is an invalid vairable name
1266 // for borland make
1267 if(static_cast<int>(ret.size()) > this->MakefileVariableSize)
1269 int keep = this->MakefileVariableSize - 8;
1270 int size = keep + 3;
1271 std::string str1 = s;
1272 std::string str2 = s2;
1273 // we must shorten the combined string by 4 charactors
1274 // keep no more than 24 charactors from the second string
1275 if(static_cast<int>(str2.size()) > keep)
1277 str2 = str2.substr(0, keep);
1279 if(static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size)
1281 str1 = str1.substr(0, size - str2.size());
1283 char buffer[5];
1284 int ni = 0;
1285 sprintf(buffer, "%04d", ni);
1286 ret = str1 + str2 + buffer;
1287 while(this->ShortMakeVariableMap.count(ret) && ni < 1000)
1289 ++ni;
1290 sprintf(buffer, "%04d", ni);
1291 ret = str1 + str2 + buffer;
1293 if(ni == 1000)
1295 cmSystemTools::Error("Borland makefile variable length too long");
1296 return unmodified;
1298 // once an unused variable is found
1299 this->ShortMakeVariableMap[ret] = "1";
1301 // always make an entry into the unmodified to variable map
1302 this->MakeVariableMap[unmodified] = ret;
1303 return ret;
1306 //----------------------------------------------------------------------------
1307 bool cmLocalUnixMakefileGenerator3::UpdateDependencies(const char* tgtInfo,
1308 bool verbose,
1309 bool color)
1311 // read in the target info file
1312 if(!this->Makefile->ReadListFile(0, tgtInfo) ||
1313 cmSystemTools::GetErrorOccuredFlag())
1315 cmSystemTools::Error("Target DependInfo.cmake file not found");
1318 // Check if any multiple output pairs have a missing file.
1319 this->CheckMultipleOutputs(verbose);
1321 std::string dir = cmSystemTools::GetFilenamePath(tgtInfo);
1322 std::string internalDependFile = dir + "/depend.internal";
1323 std::string dependFile = dir + "/depend.make";
1325 // If the target DependInfo.cmake file has changed since the last
1326 // time dependencies were scanned then force rescanning. This may
1327 // happen when a new source file is added and CMake regenerates the
1328 // project but no other sources were touched.
1329 bool needRescan = false;
1330 cmFileTimeComparison* ftc =
1331 this->GlobalGenerator->GetCMakeInstance()->GetFileComparison();
1333 int result;
1334 if(!ftc->FileTimeCompare(internalDependFile.c_str(), tgtInfo, &result) ||
1335 result < 0)
1337 if(verbose)
1339 cmOStringStream msg;
1340 msg << "Dependee \"" << tgtInfo
1341 << "\" is newer than depender \""
1342 << internalDependFile << "\"." << std::endl;
1343 cmSystemTools::Stdout(msg.str().c_str());
1345 needRescan = true;
1349 // Check the implicit dependencies to see if they are up to date.
1350 // The build.make file may have explicit dependencies for the object
1351 // files but these will not affect the scanning process so they need
1352 // not be considered.
1353 cmDependsC checker;
1354 checker.SetVerbose(verbose);
1355 checker.SetFileComparison(ftc);
1356 if(needRescan ||
1357 !checker.Check(dependFile.c_str(), internalDependFile.c_str()))
1359 // The dependencies must be regenerated.
1360 std::string targetName = cmSystemTools::GetFilenameName(dir);
1361 targetName = targetName.substr(0, targetName.length()-4);
1362 std::string message = "Scanning dependencies of target ";
1363 message += targetName;
1364 #ifdef CMAKE_BUILD_WITH_CMAKE
1365 cmSystemTools::MakefileColorEcho(
1366 cmsysTerminal_Color_ForegroundMagenta |
1367 cmsysTerminal_Color_ForegroundBold,
1368 message.c_str(), true, color);
1369 #else
1370 fprintf(stdout, "%s\n", message.c_str());
1371 #endif
1373 return this->ScanDependencies(dir.c_str());
1375 else
1377 // The dependencies are already up-to-date.
1378 return true;
1382 //----------------------------------------------------------------------------
1383 bool
1384 cmLocalUnixMakefileGenerator3
1385 ::ScanDependencies(const char* targetDir)
1387 // Read the directory information file.
1388 cmMakefile* mf = this->Makefile;
1389 bool haveDirectoryInfo = false;
1390 std::string dirInfoFile = this->Makefile->GetStartOutputDirectory();
1391 dirInfoFile += cmake::GetCMakeFilesDirectory();
1392 dirInfoFile += "/CMakeDirectoryInformation.cmake";
1393 if(mf->ReadListFile(0, dirInfoFile.c_str()) &&
1394 !cmSystemTools::GetErrorOccuredFlag())
1396 haveDirectoryInfo = true;
1399 // Lookup useful directory information.
1400 if(haveDirectoryInfo)
1402 // Test whether we need to force Unix paths.
1403 if(const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS"))
1405 if(!cmSystemTools::IsOff(force))
1407 cmSystemTools::SetForceUnixPaths(true);
1411 // Setup relative path top directories.
1412 this->RelativePathsConfigured = true;
1413 if(const char* relativePathTopSource =
1414 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE"))
1416 this->RelativePathTopSource = relativePathTopSource;
1418 if(const char* relativePathTopBinary =
1419 mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY"))
1421 this->RelativePathTopBinary = relativePathTopBinary;
1424 else
1426 cmSystemTools::Error("Directory Information file not found");
1429 // create the file stream for the depends file
1430 std::string dir = targetDir;
1432 // Open the make depends file. This should be copy-if-different
1433 // because the make tool may try to reload it needlessly otherwise.
1434 std::string ruleFileNameFull = dir;
1435 ruleFileNameFull += "/depend.make";
1436 cmGeneratedFileStream ruleFileStream(ruleFileNameFull.c_str());
1437 ruleFileStream.SetCopyIfDifferent(true);
1438 if(!ruleFileStream)
1440 return false;
1443 // Open the cmake dependency tracking file. This should not be
1444 // copy-if-different because dependencies are re-scanned when it is
1445 // older than the DependInfo.cmake.
1446 std::string internalRuleFileNameFull = dir;
1447 internalRuleFileNameFull += "/depend.internal";
1448 cmGeneratedFileStream
1449 internalRuleFileStream(internalRuleFileNameFull.c_str());
1450 if(!internalRuleFileStream)
1452 return false;
1455 this->WriteDisclaimer(ruleFileStream);
1456 this->WriteDisclaimer(internalRuleFileStream);
1458 // for each language we need to scan, scan it
1459 const char *langStr = mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES");
1460 std::vector<std::string> langs;
1461 cmSystemTools::ExpandListArgument(langStr, langs);
1462 for (std::vector<std::string>::iterator li =
1463 langs.begin(); li != langs.end(); ++li)
1465 // construct the checker
1466 std::string lang = li->c_str();
1468 // Create the scanner for this language
1469 cmDepends *scanner = 0;
1470 if(lang == "C" || lang == "CXX" || lang == "RC")
1472 // TODO: Handle RC (resource files) dependencies correctly.
1473 scanner = new cmDependsC(this, targetDir, lang.c_str());
1475 #ifdef CMAKE_BUILD_WITH_CMAKE
1476 else if(lang == "Fortran")
1478 scanner = new cmDependsFortran(this);
1480 else if(lang == "Java")
1482 scanner = new cmDependsJava();
1484 #endif
1486 if (scanner)
1488 scanner->SetLocalGenerator(this);
1489 scanner->SetFileComparison
1490 (this->GlobalGenerator->GetCMakeInstance()->GetFileComparison());
1491 scanner->SetLanguage(lang.c_str());
1492 scanner->SetTargetDirectory(dir.c_str());
1493 scanner->Write(ruleFileStream, internalRuleFileStream);
1495 // free the scanner for this language
1496 delete scanner;
1500 return true;
1503 //----------------------------------------------------------------------------
1504 void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
1506 cmMakefile* mf = this->Makefile;
1508 // Get the string listing the multiple output pairs.
1509 const char* pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
1510 if(!pairs_string)
1512 return;
1515 // Convert the string to a list and preserve empty entries.
1516 std::vector<std::string> pairs;
1517 cmSystemTools::ExpandListArgument(pairs_string, pairs, true);
1518 for(std::vector<std::string>::const_iterator i = pairs.begin();
1519 i != pairs.end() && (i+1) != pairs.end();)
1521 const std::string& depender = *i++;
1522 const std::string& dependee = *i++;
1524 // If the depender is missing then delete the dependee to make
1525 // sure both will be regenerated.
1526 if(cmSystemTools::FileExists(dependee.c_str()) &&
1527 !cmSystemTools::FileExists(depender.c_str()))
1529 if(verbose)
1531 cmOStringStream msg;
1532 msg << "Deleting primary custom command output \"" << dependee
1533 << "\" because another output \""
1534 << depender << "\" does not exist." << std::endl;
1535 cmSystemTools::Stdout(msg.str().c_str());
1537 cmSystemTools::RemoveFile(dependee.c_str());
1542 //----------------------------------------------------------------------------
1543 void cmLocalUnixMakefileGenerator3
1544 ::WriteLocalAllRules(std::ostream& ruleFileStream)
1546 this->WriteDisclaimer(ruleFileStream);
1548 // Write the main entry point target. This must be the VERY first
1549 // target so that make with no arguments will run it.
1551 // Just depend on the all target to drive the build.
1552 std::vector<std::string> depends;
1553 std::vector<std::string> no_commands;
1554 depends.push_back("all");
1556 // Write the rule.
1557 this->WriteMakeRule(ruleFileStream,
1558 "Default target executed when no arguments are "
1559 "given to make.",
1560 "default_target",
1561 depends,
1562 no_commands, true);
1565 this->WriteSpecialTargetsTop(ruleFileStream);
1567 // Include the progress variables for the target.
1568 // Write all global targets
1569 this->WriteDivider(ruleFileStream);
1570 ruleFileStream
1571 << "# Targets provided globally by CMake.\n"
1572 << "\n";
1573 cmTargets* targets = &(this->Makefile->GetTargets());
1574 cmTargets::iterator glIt;
1575 for ( glIt = targets->begin(); glIt != targets->end(); ++ glIt )
1577 if ( glIt->second.GetType() == cmTarget::GLOBAL_TARGET )
1579 std::string targetString = "Special rule for the target " + glIt->first;
1580 std::vector<std::string> commands;
1581 std::vector<std::string> depends;
1583 const char* text = glIt->second.GetProperty("EchoString");
1584 if ( !text )
1586 text = "Running external command ...";
1588 std::set<cmStdString>::const_iterator dit;
1589 for ( dit = glIt->second.GetUtilities().begin();
1590 dit != glIt->second.GetUtilities().end();
1591 ++ dit )
1593 depends.push_back(dit->c_str());
1595 this->AppendEcho(commands, text,
1596 cmLocalUnixMakefileGenerator3::EchoGlobal);
1598 // Global targets store their rules in pre- and post-build commands.
1599 this->AppendCustomDepends(depends,
1600 glIt->second.GetPreBuildCommands());
1601 this->AppendCustomDepends(depends,
1602 glIt->second.GetPostBuildCommands());
1603 this->AppendCustomCommands(commands,
1604 glIt->second.GetPreBuildCommands(),
1605 &glIt->second,
1606 cmLocalGenerator::START_OUTPUT);
1607 this->AppendCustomCommands(commands,
1608 glIt->second.GetPostBuildCommands(),
1609 &glIt->second,
1610 cmLocalGenerator::START_OUTPUT);
1611 std::string targetName = glIt->second.GetName();
1612 this->WriteMakeRule(ruleFileStream, targetString.c_str(),
1613 targetName.c_str(), depends, commands, true);
1615 // Provide a "/fast" version of the target.
1616 depends.clear();
1617 if((targetName == "install")
1618 || (targetName == "install_local")
1619 || (targetName == "install_strip"))
1621 // Provide a fast install target that does not depend on all
1622 // but has the same command.
1623 depends.push_back("preinstall/fast");
1625 else
1627 // Just forward to the real target so at least it will work.
1628 depends.push_back(targetName);
1629 commands.clear();
1631 targetName += "/fast";
1632 this->WriteMakeRule(ruleFileStream, targetString.c_str(),
1633 targetName.c_str(), depends, commands, true);
1637 std::vector<std::string> depends;
1638 std::vector<std::string> commands;
1640 // Write the all rule.
1641 std::string dir;
1642 std::string recursiveTarget = this->Makefile->GetStartOutputDirectory();
1643 recursiveTarget += "/all";
1645 depends.push_back("cmake_check_build_system");
1647 std::string progressDir = this->Makefile->GetHomeOutputDirectory();
1648 progressDir += cmake::GetCMakeFilesDirectory();
1650 cmOStringStream progCmd;
1651 progCmd <<
1652 "$(CMAKE_COMMAND) -E cmake_progress_start ";
1653 progCmd << this->Convert(progressDir.c_str(),
1654 cmLocalGenerator::FULL,
1655 cmLocalGenerator::SHELL);
1657 std::string progressFile = cmake::GetCMakeFilesDirectory();
1658 progressFile += "/progress.marks";
1659 std::string progressFileNameFull =
1660 this->ConvertToFullPath(progressFile.c_str());
1661 progCmd << " " << this->Convert(progressFileNameFull.c_str(),
1662 cmLocalGenerator::FULL,
1663 cmLocalGenerator::SHELL);
1664 commands.push_back(progCmd.str());
1666 std::string mf2Dir = cmake::GetCMakeFilesDirectoryPostSlash();
1667 mf2Dir += "Makefile2";
1668 commands.push_back(this->GetRecursiveMakeCall(mf2Dir.c_str(),
1669 recursiveTarget.c_str()));
1670 this->CreateCDCommand(commands,
1671 this->Makefile->GetHomeOutputDirectory(),
1672 cmLocalGenerator::START_OUTPUT);
1674 cmOStringStream progCmd;
1675 progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
1676 progCmd << this->Convert(progressDir.c_str(),
1677 cmLocalGenerator::FULL,
1678 cmLocalGenerator::SHELL);
1679 progCmd << " 0";
1680 commands.push_back(progCmd.str());
1682 this->WriteMakeRule(ruleFileStream, "The main all target", "all",
1683 depends, commands, true);
1685 // Write the clean rule.
1686 recursiveTarget = this->Makefile->GetStartOutputDirectory();
1687 recursiveTarget += "/clean";
1688 commands.clear();
1689 depends.clear();
1690 commands.push_back(this->GetRecursiveMakeCall(mf2Dir.c_str(),
1691 recursiveTarget.c_str()));
1692 this->CreateCDCommand(commands,
1693 this->Makefile->GetHomeOutputDirectory(),
1694 cmLocalGenerator::START_OUTPUT);
1695 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
1696 depends, commands, true);
1697 commands.clear();
1698 depends.clear();
1699 depends.push_back("clean");
1700 this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
1701 depends, commands, true);
1703 // Write the preinstall rule.
1704 recursiveTarget = this->Makefile->GetStartOutputDirectory();
1705 recursiveTarget += "/preinstall";
1706 commands.clear();
1707 depends.clear();
1708 const char* noall =
1709 this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
1710 if(!noall || cmSystemTools::IsOff(noall))
1712 // Drive the build before installing.
1713 depends.push_back("all");
1715 else
1717 // At least make sure the build system is up to date.
1718 depends.push_back("cmake_check_build_system");
1720 commands.push_back
1721 (this->GetRecursiveMakeCall(mf2Dir.c_str(), recursiveTarget.c_str()));
1722 this->CreateCDCommand(commands,
1723 this->Makefile->GetHomeOutputDirectory(),
1724 cmLocalGenerator::START_OUTPUT);
1725 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1726 "preinstall", depends, commands, true);
1727 depends.clear();
1728 this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1729 "preinstall/fast", depends, commands, true);
1731 // write the depend rule, really a recompute depends rule
1732 depends.clear();
1733 commands.clear();
1734 std::string cmakefileName = cmake::GetCMakeFilesDirectoryPostSlash();
1735 cmakefileName += "Makefile.cmake";
1736 std::string runRule =
1737 "$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)";
1738 runRule += " --check-build-system ";
1739 runRule += this->Convert(cmakefileName.c_str(),cmLocalGenerator::NONE,
1740 cmLocalGenerator::SHELL);
1741 runRule += " 1";
1742 commands.push_back(runRule);
1743 this->CreateCDCommand(commands,
1744 this->Makefile->GetHomeOutputDirectory(),
1745 cmLocalGenerator::START_OUTPUT);
1746 this->WriteMakeRule(ruleFileStream, "clear depends",
1747 "depend",
1748 depends, commands, true);
1752 //----------------------------------------------------------------------------
1753 void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
1754 bool verbose)
1756 // Get the list of target files to check
1757 const char* infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
1758 if(!infoDef)
1760 return;
1762 std::vector<std::string> files;
1763 cmSystemTools::ExpandListArgument(infoDef, files);
1765 // Each depend information file corresponds to a target. Clear the
1766 // dependencies for that target.
1767 cmDepends clearer;
1768 clearer.SetVerbose(verbose);
1769 for(std::vector<std::string>::iterator l = files.begin();
1770 l != files.end(); ++l)
1772 std::string dir = cmSystemTools::GetFilenamePath(l->c_str());
1774 // Clear the implicit dependency makefile.
1775 std::string dependFile = dir + "/depend.make";
1776 clearer.Clear(dependFile.c_str());
1778 // Remove the internal dependency check file to force
1779 // regeneration.
1780 std::string internalDependFile = dir + "/depend.internal";
1781 cmSystemTools::RemoveFile(internalDependFile.c_str());
1786 void cmLocalUnixMakefileGenerator3
1787 ::WriteDependLanguageInfo(std::ostream& cmakefileStream, cmTarget &target)
1789 ImplicitDependLanguageMap const& implicitLangs =
1790 this->GetImplicitDepends(target);
1792 // list the languages
1793 cmakefileStream
1794 << "# The set of languages for which implicit dependencies are needed:\n";
1795 cmakefileStream
1796 << "SET(CMAKE_DEPENDS_LANGUAGES\n";
1797 for(ImplicitDependLanguageMap::const_iterator
1798 l = implicitLangs.begin(); l != implicitLangs.end(); ++l)
1800 cmakefileStream << " \"" << l->first.c_str() << "\"\n";
1802 cmakefileStream << " )\n";
1804 // now list the files for each language
1805 cmakefileStream
1806 << "# The set of files for implicit dependencies of each language:\n";
1807 for(ImplicitDependLanguageMap::const_iterator
1808 l = implicitLangs.begin(); l != implicitLangs.end(); ++l)
1810 cmakefileStream
1811 << "SET(CMAKE_DEPENDS_CHECK_" << l->first.c_str() << "\n";
1812 ImplicitDependFileMap const& implicitPairs = l->second;
1814 // for each file pair
1815 for(ImplicitDependFileMap::const_iterator pi = implicitPairs.begin();
1816 pi != implicitPairs.end(); ++pi)
1818 cmakefileStream << " \"" << pi->second << "\" ";
1819 cmakefileStream << "\"" << pi->first << "\"\n";
1821 cmakefileStream << " )\n";
1823 // Tell the dependency scanner what compiler is used.
1824 std::string cidVar = "CMAKE_";
1825 cidVar += l->first;
1826 cidVar += "_COMPILER_ID";
1827 const char* cid = this->Makefile->GetDefinition(cidVar.c_str());
1828 if(cid && *cid)
1830 cmakefileStream
1831 << "SET(CMAKE_" << l->first.c_str() << "_COMPILER_ID \""
1832 << cid << "\")\n";
1836 // Build a list of preprocessor definitions for the target.
1837 std::vector<std::string> defines;
1839 std::string defPropName = "COMPILE_DEFINITIONS_";
1840 defPropName += cmSystemTools::UpperCase(this->ConfigurationName);
1841 if(const char* ddefs = this->Makefile->GetProperty("COMPILE_DEFINITIONS"))
1843 cmSystemTools::ExpandListArgument(ddefs, defines);
1845 if(const char* cdefs = target.GetProperty("COMPILE_DEFINITIONS"))
1847 cmSystemTools::ExpandListArgument(cdefs, defines);
1849 if(const char* dcdefs = this->Makefile->GetProperty(defPropName.c_str()))
1851 cmSystemTools::ExpandListArgument(dcdefs, defines);
1853 if(const char* ccdefs = target.GetProperty(defPropName.c_str()))
1855 cmSystemTools::ExpandListArgument(ccdefs, defines);
1858 if(!defines.empty())
1860 cmakefileStream
1861 << "\n"
1862 << "# Preprocessor definitions for this target.\n"
1863 << "SET(CMAKE_TARGET_DEFINITIONS\n";
1864 for(std::vector<std::string>::const_iterator di = defines.begin();
1865 di != defines.end(); ++di)
1867 cmakefileStream
1868 << " " << this->EscapeForCMake(di->c_str()) << "\n";
1870 cmakefileStream
1871 << " )\n";
1874 // Store include transform rule properties. Write the directory
1875 // rules first because they may be overridden by later target rules.
1876 std::vector<std::string> transformRules;
1877 if(const char* xform =
1878 this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM"))
1880 cmSystemTools::ExpandListArgument(xform, transformRules);
1882 if(const char* xform =
1883 target.GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM"))
1885 cmSystemTools::ExpandListArgument(xform, transformRules);
1887 if(!transformRules.empty())
1889 cmakefileStream
1890 << "SET(CMAKE_INCLUDE_TRANSFORMS\n";
1891 for(std::vector<std::string>::const_iterator tri = transformRules.begin();
1892 tri != transformRules.end(); ++tri)
1894 cmakefileStream << " " << this->EscapeForCMake(tri->c_str()) << "\n";
1896 cmakefileStream
1897 << " )\n";
1901 //----------------------------------------------------------------------------
1902 std::string
1903 cmLocalUnixMakefileGenerator3
1904 ::GetObjectFileName(cmTarget& target,
1905 const cmSourceFile& source,
1906 std::string* nameWithoutTargetDir,
1907 bool* hasSourceExtension)
1909 // Make sure we never hit this old case.
1910 if(source.GetProperty("MACOSX_PACKAGE_LOCATION"))
1912 std::string msg = "MACOSX_PACKAGE_LOCATION set on source file: ";
1913 msg += source.GetFullPath();
1914 this->GetMakefile()->IssueMessage(cmake::INTERNAL_ERROR,
1915 msg.c_str());
1918 // Start with the target directory.
1919 std::string obj = this->GetTargetDirectory(target);
1920 obj += "/";
1922 // Get the object file name without the target directory.
1923 std::string dir_max;
1924 dir_max += this->Makefile->GetCurrentOutputDirectory();
1925 dir_max += "/";
1926 dir_max += obj;
1927 std::string objectName =
1928 this->GetObjectFileNameWithoutTarget(source, dir_max,
1929 hasSourceExtension);
1930 if(nameWithoutTargetDir)
1932 *nameWithoutTargetDir = objectName;
1935 // Append the object name to the target directory.
1936 obj += objectName;
1937 return obj;
1940 //----------------------------------------------------------------------------
1941 void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
1944 << "# CMAKE generated file: DO NOT EDIT!\n"
1945 << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
1946 << " Generator, CMake Version "
1947 << cmVersion::GetMajorVersion() << "."
1948 << cmVersion::GetMinorVersion() << "\n\n";
1951 //----------------------------------------------------------------------------
1952 std::string
1953 cmLocalUnixMakefileGenerator3
1954 ::GetRecursiveMakeCall(const char *makefile, const char* tgt)
1956 // Call make on the given file.
1957 std::string cmd;
1958 cmd += "$(MAKE) -f ";
1959 cmd += this->Convert(makefile,NONE,SHELL);
1960 cmd += " ";
1962 // Pass down verbosity level.
1963 if(this->GetMakeSilentFlag().size())
1965 cmd += this->GetMakeSilentFlag();
1966 cmd += " ";
1969 // Most unix makes will pass the command line flags to make down to
1970 // sub-invoked makes via an environment variable. However, some
1971 // makes do not support that, so you have to pass the flags
1972 // explicitly.
1973 if(this->GetPassMakeflags())
1975 cmd += "-$(MAKEFLAGS) ";
1978 // Add the target.
1979 if (tgt && tgt[0] != '\0')
1981 // The make target is always relative to the top of the build tree.
1982 std::string tgt2 = this->Convert(tgt, HOME_OUTPUT);
1984 // The target may have been written with windows paths.
1985 cmSystemTools::ConvertToOutputSlashes(tgt2);
1987 // Escape one extra time if the make tool requires it.
1988 if(this->MakeCommandEscapeTargetTwice)
1990 tgt2 = this->EscapeForShell(tgt2.c_str(), true, false);
1993 // The target name is now a string that should be passed verbatim
1994 // on the command line.
1995 cmd += this->EscapeForShell(tgt2.c_str(), true, false);
1997 return cmd;
2000 //----------------------------------------------------------------------------
2001 void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
2004 << "#======================================"
2005 << "=======================================\n";
2008 //----------------------------------------------------------------------------
2009 void
2010 cmLocalUnixMakefileGenerator3
2011 ::WriteCMakeArgument(std::ostream& os, const char* s)
2013 // Write the given string to the stream with escaping to get it back
2014 // into CMake through the lexical scanner.
2015 os << "\"";
2016 for(const char* c = s; *c; ++c)
2018 if(*c == '\\')
2020 os << "\\\\";
2022 else if(*c == '"')
2024 os << "\\\"";
2026 else
2028 os << *c;
2031 os << "\"";
2034 //----------------------------------------------------------------------------
2035 std::string
2036 cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(const char* p)
2039 // Split the path into its components.
2040 std::vector<std::string> components;
2041 cmSystemTools::SplitPath(p, components);
2043 // Return an empty path if there are no components.
2044 if(components.empty())
2046 return "\"\"";
2049 // Choose a slash direction and fix root component.
2050 const char* slash = "/";
2051 #if defined(_WIN32) && !defined(__CYGWIN__)
2052 if(!cmSystemTools::GetForceUnixPaths())
2054 slash = "\\";
2055 for(std::string::iterator i = components[0].begin();
2056 i != components[0].end(); ++i)
2058 if(*i == '/')
2060 *i = '\\';
2064 #endif
2066 // Begin the quoted result with the root component.
2067 std::string result = "\"";
2068 result += components[0];
2070 // Now add the rest of the components separated by the proper slash
2071 // direction for this platform.
2072 bool first = true;
2073 for(unsigned int i=1; i < components.size(); ++i)
2075 // Only the last component can be empty to avoid double slashes.
2076 if(components[i].length() > 0 || (i == (components.size()-1)))
2078 if(!first)
2080 result += slash;
2082 result += components[i];
2083 first = false;
2087 // Close the quoted result.
2088 result += "\"";
2090 return result;
2093 //----------------------------------------------------------------------------
2094 std::string
2095 cmLocalUnixMakefileGenerator3
2096 ::GetTargetDirectory(cmTarget const& target) const
2098 std::string dir = cmake::GetCMakeFilesDirectoryPostSlash();
2099 dir += target.GetName();
2100 #if defined(__VMS)
2101 dir += "_dir";
2102 #else
2103 dir += ".dir";
2104 #endif
2105 return dir;
2108 //----------------------------------------------------------------------------
2109 cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
2110 cmLocalUnixMakefileGenerator3::GetImplicitDepends(cmTarget const& tgt)
2112 return this->ImplicitDepends[tgt.GetName()];
2115 //----------------------------------------------------------------------------
2116 void
2117 cmLocalUnixMakefileGenerator3::AddImplicitDepends(cmTarget const& tgt,
2118 const char* lang,
2119 const char* obj,
2120 const char* src)
2122 this->ImplicitDepends[tgt.GetName()][lang][obj] = src;
2125 //----------------------------------------------------------------------------
2126 void cmLocalUnixMakefileGenerator3
2127 ::CreateCDCommand(std::vector<std::string>& commands, const char *tgtDir,
2128 cmLocalGenerator::RelativeRoot relRetDir)
2130 const char* retDir = this->GetRelativeRootPath(relRetDir);
2132 // do we need to cd?
2133 if (!strcmp(tgtDir,retDir))
2135 return;
2138 if(!this->UnixCD)
2140 // On Windows we must perform each step separately and then change
2141 // back because the shell keeps the working directory between
2142 // commands.
2143 std::string cmd = "cd ";
2144 cmd += this->ConvertToOutputForExisting(tgtDir, relRetDir);
2145 commands.insert(commands.begin(),cmd);
2147 // Change back to the starting directory.
2148 cmd = "cd ";
2149 cmd += this->ConvertToOutputForExisting(relRetDir, tgtDir);
2150 commands.push_back(cmd);
2152 else
2154 // On UNIX we must construct a single shell command to change
2155 // directory and build because make resets the directory between
2156 // each command.
2157 std::vector<std::string>::iterator i = commands.begin();
2158 for (; i != commands.end(); ++i)
2160 std::string cmd = "cd ";
2161 cmd += this->ConvertToOutputForExisting(tgtDir, relRetDir);
2162 cmd += " && ";
2163 cmd += *i;
2164 *i = cmd;
2170 void cmLocalUnixMakefileGenerator3
2171 ::GetTargetObjectFileDirectories(cmTarget* target,
2172 std::vector<std::string>& dirs)
2174 std::string dir = this->Makefile->GetCurrentOutputDirectory();
2175 dir += "/";
2176 dir += this->GetTargetDirectory(*target);
2177 dirs.push_back(dir);