Resync
[CMakeLuaTailorHgBridge.git] / CMakeLua / Source / cmLocalGenerator.cxx
blobcbf294e1fa6131718a4c39197d1db44f44b18f16
1 /*=========================================================================
3 Program: CMake - Cross-Platform Makefile Generator
4 Module: $RCSfile: cmLocalGenerator.cxx,v $
5 Language: C++
6 Date: $Date: 2008/03/01 14:08:34 $
7 Version: $Revision: 1.266 $
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 "cmLocalGenerator.h"
19 #include "cmComputeLinkInformation.h"
20 #include "cmGeneratedFileStream.h"
21 #include "cmGlobalGenerator.h"
22 #include "cmInstallGenerator.h"
23 #include "cmInstallFilesGenerator.h"
24 #include "cmInstallScriptGenerator.h"
25 #include "cmInstallTargetGenerator.h"
26 #include "cmMakefile.h"
27 #include "cmSourceFile.h"
28 #include "cmTest.h"
29 #include "cmake.h"
31 #if defined(CMAKE_BUILD_WITH_CMAKE)
32 # define CM_LG_ENCODE_OBJECT_NAMES
33 # include <cmsys/MD5.h>
34 #endif
36 #include <cmsys/System.h>
38 #include <ctype.h> // for isalpha
40 #include <assert.h>
42 cmLocalGenerator::cmLocalGenerator()
44 this->Makefile = new cmMakefile;
45 this->Makefile->SetLocalGenerator(this);
46 this->Parent = 0;
47 this->WindowsShell = false;
48 this->WindowsVSIDE = false;
49 this->WatcomWMake = false;
50 this->MinGWMake = false;
51 this->NMake = false;
52 this->MSYSShell = false;
53 this->LinkScriptShell = false;
54 this->IgnoreLibPrefix = false;
55 this->UseRelativePaths = false;
56 this->Configured = false;
57 this->EmitUniversalBinaryFlags = true;
58 this->IsMakefileGenerator = false;
59 this->RelativePathsConfigured = false;
60 this->PathConversionsSetup = false;
61 this->BackwardsCompatibility = 0;
62 this->BackwardsCompatibilityFinal = false;
65 cmLocalGenerator::~cmLocalGenerator()
67 delete this->Makefile;
70 void cmLocalGenerator::Configure()
72 cmLocalGenerator* previousLg =
73 this->GetGlobalGenerator()->GetCurrentLocalGenerator();
74 this->GetGlobalGenerator()->SetCurrentLocalGenerator(this);
76 // make sure the CMakeFiles dir is there
77 std::string filesDir = this->Makefile->GetStartOutputDirectory();
78 filesDir += cmake::GetCMakeFilesDirectory();
79 cmSystemTools::MakeDirectory(filesDir.c_str());
81 // find & read the list file
82 std::string currentStart = this->Makefile->GetStartDirectory();
83 currentStart += "/CMakeLists.txt";
84 this->Makefile->ReadListFile(currentStart.c_str());
86 // at the end of the ReadListFile handle any old style subdirs
87 // first get all the subdirectories
88 std::vector<cmLocalGenerator *> subdirs = this->GetChildren();
90 // for each subdir recurse
91 std::vector<cmLocalGenerator *>::iterator sdi = subdirs.begin();
92 for (; sdi != subdirs.end(); ++sdi)
94 if (!(*sdi)->Configured)
96 this->Makefile->ConfigureSubDirectory(*sdi);
100 // Check whether relative paths should be used for optionally
101 // relative paths.
102 this->UseRelativePaths = this->Makefile->IsOn("CMAKE_USE_RELATIVE_PATHS");
104 this->Configured = true;
106 this->GetGlobalGenerator()->SetCurrentLocalGenerator(previousLg);
109 void cmLocalGenerator::SetupPathConversions()
111 // Setup the current output directory components for use by
112 // Convert
113 std::string outdir;
114 outdir =
115 cmSystemTools::CollapseFullPath(this->Makefile->GetHomeDirectory());
116 cmSystemTools::SplitPath(outdir.c_str(), this->HomeDirectoryComponents);
117 outdir =
118 cmSystemTools::CollapseFullPath(this->Makefile->GetStartDirectory());
119 cmSystemTools::SplitPath(outdir.c_str(), this->StartDirectoryComponents);
121 outdir = cmSystemTools::CollapseFullPath
122 (this->Makefile->GetHomeOutputDirectory());
123 cmSystemTools::SplitPath(outdir.c_str(),
124 this->HomeOutputDirectoryComponents);
126 outdir = cmSystemTools::CollapseFullPath
127 (this->Makefile->GetStartOutputDirectory());
128 cmSystemTools::SplitPath(outdir.c_str(),
129 this->StartOutputDirectoryComponents);
133 void cmLocalGenerator::SetGlobalGenerator(cmGlobalGenerator *gg)
135 this->GlobalGenerator = gg;
137 // setup the home directories
138 this->Makefile->GetProperties().SetCMakeInstance(gg->GetCMakeInstance());
139 this->Makefile->SetHomeDirectory(
140 gg->GetCMakeInstance()->GetHomeDirectory());
141 this->Makefile->SetHomeOutputDirectory(
142 gg->GetCMakeInstance()->GetHomeOutputDirectory());
145 void cmLocalGenerator::ConfigureFinalPass()
147 this->Makefile->ConfigureFinalPass();
150 void cmLocalGenerator::TraceDependencies()
152 // Generate the rule files for each target.
153 cmTargets& targets = this->Makefile->GetTargets();
154 for(cmTargets::iterator t = targets.begin(); t != targets.end(); ++t)
156 // INCLUDE_EXTERNAL_MSPROJECT command only affects the workspace
157 // so don't build a projectfile for it
158 if (strncmp(t->first.c_str(), "INCLUDE_EXTERNAL_MSPROJECT", 26) != 0)
160 const char* projectFilename = 0;
161 if (this->IsMakefileGenerator == false) // only use of this variable
163 projectFilename = t->second.GetName();
165 t->second.TraceDependencies(projectFilename);
170 void cmLocalGenerator::GenerateTestFiles()
172 if ( !this->Makefile->IsOn("CMAKE_TESTING_ENABLED") )
174 return;
176 std::string file = this->Makefile->GetStartOutputDirectory();
177 file += "/";
178 file += "CTestTestfile.cmake";
180 cmGeneratedFileStream fout(file.c_str());
181 fout.SetCopyIfDifferent(true);
183 fout << "# CMake generated Testfile for " << std::endl
184 << "# Source directory: "
185 << this->Makefile->GetStartDirectory() << std::endl
186 << "# Build directory: "
187 << this->Makefile->GetStartOutputDirectory() << std::endl
188 << "# " << std::endl
189 << "# This file replicates the SUBDIRS() and ADD_TEST() commands "
190 << "from the source" << std::endl
191 << "# tree CMakeLists.txt file, skipping any SUBDIRS() or "
192 << "ADD_TEST() commands" << std::endl
193 << "# that are excluded by CMake control structures, i.e. IF() "
194 << "commands." << std::endl;
196 const char* testIncludeFile =
197 this->Makefile->GetProperty("TEST_INCLUDE_FILE");
198 if ( testIncludeFile )
200 fout << "INCLUDE(\"" << testIncludeFile << "\")" << std::endl;
203 const std::vector<cmTest*> *tests = this->Makefile->GetTests();
204 std::vector<cmTest*>::const_iterator it;
205 for ( it = tests->begin(); it != tests->end(); ++ it )
207 cmTest* test = *it;
208 fout << "ADD_TEST(";
209 fout << test->GetName() << " \"" << test->GetCommand() << "\"";
211 std::vector<cmStdString>::const_iterator argit;
212 for (argit = test->GetArguments().begin();
213 argit != test->GetArguments().end(); ++argit)
215 // Just double-quote all arguments so they are re-parsed
216 // correctly by the test system.
217 fout << " \"";
218 for(std::string::const_iterator c = argit->begin();
219 c != argit->end(); ++c)
221 // Escape quotes within arguments. We should escape
222 // backslashes too but we cannot because it makes the result
223 // inconsistent with previous behavior of this command.
224 if((*c == '"'))
226 fout << '\\';
228 fout << *c;
230 fout << "\"";
232 fout << ")" << std::endl;
233 cmPropertyMap::const_iterator pit;
234 cmPropertyMap* mpit = &test->GetProperties();
235 if ( mpit->size() )
237 fout << "SET_TESTS_PROPERTIES(" << test->GetName() << " PROPERTIES ";
238 for ( pit = mpit->begin(); pit != mpit->end(); ++ pit )
240 fout << " " << pit->first.c_str() << " \"";
241 const char* value = pit->second.GetValue();
242 for ( ; *value; ++ value )
244 switch ( *value )
246 case '\\':
247 case '"':
248 case ' ':
249 case '#':
250 case '(':
251 case ')':
252 case '$':
253 case '^':
254 fout << "\\" << *value;
255 break;
256 case '\t':
257 fout << "\\t";
258 break;
259 case '\n':
260 fout << "\\n";
261 break;
262 case '\r':
263 fout << "\\r";
264 break;
265 default:
266 fout << *value;
269 fout << "\"";
271 fout << ")" << std::endl;
274 if ( this->Children.size())
276 size_t i;
277 for(i = 0; i < this->Children.size(); ++i)
279 fout << "SUBDIRS(";
280 std::string outP =
281 this->Children[i]->GetMakefile()->GetStartOutputDirectory();
282 fout << this->Convert(outP.c_str(),START_OUTPUT);
283 fout << ")" << std::endl;
288 //----------------------------------------------------------------------------
289 void cmLocalGenerator::GenerateInstallRules()
291 // Compute the install prefix.
292 const char* prefix = this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
293 #if defined(_WIN32) && !defined(__CYGWIN__)
294 std::string prefix_win32;
295 if(!prefix)
297 if(!cmSystemTools::GetEnv("SystemDrive", prefix_win32))
299 prefix_win32 = "C:";
301 const char* project_name = this->Makefile->GetDefinition("PROJECT_NAME");
302 if(project_name && project_name[0])
304 prefix_win32 += "/Program Files/";
305 prefix_win32 += project_name;
307 else
309 prefix_win32 += "/InstalledCMakeProject";
311 prefix = prefix_win32.c_str();
313 #else
314 if (!prefix)
316 prefix = "/usr/local";
318 #endif
320 // Compute the set of configurations.
321 std::vector<std::string> configurationTypes;
322 if(const char* types =
323 this->Makefile->GetDefinition("CMAKE_CONFIGURATION_TYPES"))
325 cmSystemTools::ExpandListArgument(types, configurationTypes);
327 const char* config = 0;
328 if(configurationTypes.empty())
330 config = this->Makefile->GetDefinition("CMAKE_BUILD_TYPE");
333 // Choose a default install configuration.
334 const char* default_config = config;
335 const char* default_order[] = {"RELEASE", "MINSIZEREL",
336 "RELWITHDEBINFO", "DEBUG", 0};
337 for(const char** c = default_order; *c && !default_config; ++c)
339 for(std::vector<std::string>::iterator i = configurationTypes.begin();
340 i != configurationTypes.end(); ++i)
342 if(cmSystemTools::UpperCase(*i) == *c)
344 default_config = i->c_str();
348 if(!default_config && !configurationTypes.empty())
350 default_config = configurationTypes[0].c_str();
352 if(!default_config)
354 default_config = "Release";
357 // Create the install script file.
358 std::string file = this->Makefile->GetStartOutputDirectory();
359 std::string homedir = this->Makefile->GetHomeOutputDirectory();
360 std::string currdir = this->Makefile->GetCurrentOutputDirectory();
361 cmSystemTools::ConvertToUnixSlashes(file);
362 cmSystemTools::ConvertToUnixSlashes(homedir);
363 cmSystemTools::ConvertToUnixSlashes(currdir);
364 int toplevel_install = 0;
365 if ( currdir == homedir )
367 toplevel_install = 1;
369 file += "/cmake_install.cmake";
370 cmGeneratedFileStream fout(file.c_str());
371 fout.SetCopyIfDifferent(true);
373 // Write the header.
374 fout << "# Install script for directory: "
375 << this->Makefile->GetCurrentDirectory() << std::endl << std::endl;
376 fout << "# Set the install prefix" << std::endl
377 << "IF(NOT DEFINED CMAKE_INSTALL_PREFIX)" << std::endl
378 << " SET(CMAKE_INSTALL_PREFIX \"" << prefix << "\")" << std::endl
379 << "ENDIF(NOT DEFINED CMAKE_INSTALL_PREFIX)" << std::endl
380 << "STRING(REGEX REPLACE \"/$\" \"\" CMAKE_INSTALL_PREFIX "
381 << "\"${CMAKE_INSTALL_PREFIX}\")" << std::endl
382 << std::endl;
384 // Write support code for generating per-configuration install rules.
385 fout <<
386 "# Set the install configuration name.\n"
387 "IF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
388 " IF(BUILD_TYPE)\n"
389 " STRING(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
390 " CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
391 " ELSE(BUILD_TYPE)\n"
392 " SET(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
393 " ENDIF(BUILD_TYPE)\n"
394 " MESSAGE(STATUS \"Install configuration: "
395 "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
396 "ENDIF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
397 "\n";
399 // Write support code for dealing with component-specific installs.
400 fout <<
401 "# Set the component getting installed.\n"
402 "IF(NOT CMAKE_INSTALL_COMPONENT)\n"
403 " IF(COMPONENT)\n"
404 " MESSAGE(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
405 " SET(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
406 " ELSE(COMPONENT)\n"
407 " SET(CMAKE_INSTALL_COMPONENT)\n"
408 " ENDIF(COMPONENT)\n"
409 "ENDIF(NOT CMAKE_INSTALL_COMPONENT)\n"
410 "\n";
412 // Copy user-specified install options to the install code.
413 if(const char* so_no_exe =
414 this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE"))
416 fout <<
417 "# Install shared libraries without execute permission?\n"
418 "IF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
419 " SET(CMAKE_INSTALL_SO_NO_EXE \"" << so_no_exe << "\")\n"
420 "ENDIF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
421 "\n";
424 // Ask each install generator to write its code.
425 std::vector<cmInstallGenerator*> const& installers =
426 this->Makefile->GetInstallGenerators();
427 for(std::vector<cmInstallGenerator*>::const_iterator
428 gi = installers.begin();
429 gi != installers.end(); ++gi)
431 (*gi)->Generate(fout, config, configurationTypes);
434 // Write rules from old-style specification stored in targets.
435 this->GenerateTargetInstallRules(fout, config, configurationTypes);
437 // Include install scripts from subdirectories.
438 if(!this->Children.empty())
440 fout << "IF(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
441 fout << " # Include the install script for each subdirectory.\n";
442 for(std::vector<cmLocalGenerator*>::const_iterator
443 ci = this->Children.begin(); ci != this->Children.end(); ++ci)
445 if(!(*ci)->GetMakefile()->GetPropertyAsBool("EXCLUDE_FROM_ALL"))
447 std::string odir = (*ci)->GetMakefile()->GetStartOutputDirectory();
448 cmSystemTools::ConvertToUnixSlashes(odir);
449 fout << " INCLUDE(\"" << odir.c_str()
450 << "/cmake_install.cmake\")" << std::endl;
453 fout << "\n";
454 fout << "ENDIF(NOT CMAKE_INSTALL_LOCAL_ONLY)\n\n";
457 // Record the install manifest.
458 if ( toplevel_install )
460 fout <<
461 "IF(CMAKE_INSTALL_COMPONENT)\n"
462 " SET(CMAKE_INSTALL_MANIFEST \"install_manifest_"
463 "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
464 "ELSE(CMAKE_INSTALL_COMPONENT)\n"
465 " SET(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
466 "ENDIF(CMAKE_INSTALL_COMPONENT)\n\n";
467 fout
468 << "FILE(WRITE \""
469 << homedir.c_str() << "/${CMAKE_INSTALL_MANIFEST}\" "
470 << "\"\")" << std::endl;
471 fout
472 << "FOREACH(file ${CMAKE_INSTALL_MANIFEST_FILES})" << std::endl
473 << " FILE(APPEND \""
474 << homedir.c_str() << "/${CMAKE_INSTALL_MANIFEST}\" "
475 << "\"${file}\\n\")" << std::endl
476 << "ENDFOREACH(file)" << std::endl;
480 //----------------------------------------------------------------------------
481 void cmLocalGenerator::GenerateTargetManifest()
483 // Collect the set of configuration types.
484 std::vector<std::string> configNames;
485 if(const char* configurationTypes =
486 this->Makefile->GetDefinition("CMAKE_CONFIGURATION_TYPES"))
488 cmSystemTools::ExpandListArgument(configurationTypes, configNames);
490 else if(const char* buildType =
491 this->Makefile->GetDefinition("CMAKE_BUILD_TYPE"))
493 if(*buildType)
495 configNames.push_back(buildType);
499 // Add our targets to the manifest for each configuration.
500 cmTargets& targets = this->Makefile->GetTargets();
501 for(cmTargets::iterator t = targets.begin(); t != targets.end(); ++t)
503 cmTarget& target = t->second;
504 if(configNames.empty())
506 target.GenerateTargetManifest(0);
508 else
510 for(std::vector<std::string>::iterator ci = configNames.begin();
511 ci != configNames.end(); ++ci)
513 const char* config = ci->c_str();
514 target.GenerateTargetManifest(config);
520 void cmLocalGenerator::AddCustomCommandToCreateObject(const char* ofname,
521 const char* lang,
522 cmSourceFile& source,
523 cmTarget& )
525 std::string objectDir = cmSystemTools::GetFilenamePath(std::string(ofname));
526 objectDir = this->Convert(objectDir.c_str(),START_OUTPUT,SHELL);
527 std::string objectFile = this->Convert(ofname,START_OUTPUT,SHELL);
528 std::string sourceFile =
529 this->Convert(source.GetFullPath().c_str(),START_OUTPUT,SHELL,true);
530 std::string varString = "CMAKE_";
531 varString += lang;
532 varString += "_COMPILE_OBJECT";
533 std::vector<std::string> rules;
534 rules.push_back(this->Makefile->GetRequiredDefinition(varString.c_str()));
535 varString = "CMAKE_";
536 varString += lang;
537 varString += "_FLAGS";
538 std::string flags;
539 flags += this->Makefile->GetSafeDefinition(varString.c_str());
540 flags += " ";
541 flags += this->GetIncludeFlags(lang);
543 // Construct the command lines.
544 cmCustomCommandLines commandLines;
545 std::vector<std::string> commands;
546 cmSystemTools::ExpandList(rules, commands);
547 cmLocalGenerator::RuleVariables vars;
548 vars.Language = lang;
549 vars.Source = sourceFile.c_str();
550 vars.Object = objectFile.c_str();
551 vars.ObjectDir = objectDir.c_str();
552 vars.Flags = flags.c_str();
553 for(std::vector<std::string>::iterator i = commands.begin();
554 i != commands.end(); ++i)
556 // Expand the full command line string.
557 this->ExpandRuleVariables(*i, vars);
559 // Parse the string to get the custom command line.
560 cmCustomCommandLine commandLine;
561 std::vector<cmStdString> cmd = cmSystemTools::ParseArguments(i->c_str());
562 for(std::vector<cmStdString>::iterator a = cmd.begin();
563 a != cmd.end(); ++a)
565 commandLine.push_back(*a);
568 // Store this command line.
569 commandLines.push_back(commandLine);
572 // Check for extra object-file dependencies.
573 std::vector<std::string> depends;
574 const char* additionalDeps = source.GetProperty("OBJECT_DEPENDS");
575 if(additionalDeps)
577 cmSystemTools::ExpandListArgument(additionalDeps, depends);
580 // Generate a meaningful comment for the command.
581 std::string comment = "Building ";
582 comment += lang;
583 comment += " object ";
584 comment += this->Convert(ofname, START_OUTPUT);
586 // Add the custom command to build the object file.
587 this->Makefile->AddCustomCommandToOutput(
588 ofname,
589 depends,
590 source.GetFullPath().c_str(),
591 commandLines,
592 comment.c_str(),
593 this->Makefile->GetStartOutputDirectory()
597 void cmLocalGenerator::AddBuildTargetRule(const char* llang, cmTarget& target)
599 cmStdString objs;
600 std::vector<std::string> objVector;
601 // Add all the sources outputs to the depends of the target
602 std::vector<cmSourceFile*> const& classes = target.GetSourceFiles();
603 for(std::vector<cmSourceFile*>::const_iterator i = classes.begin();
604 i != classes.end(); ++i)
606 cmSourceFile* sf = *i;
607 if(!sf->GetCustomCommand() &&
608 !sf->GetPropertyAsBool("HEADER_FILE_ONLY") &&
609 !sf->GetPropertyAsBool("EXTERNAL_OBJECT"))
611 std::string::size_type dir_len = 0;
612 dir_len += strlen(this->Makefile->GetCurrentOutputDirectory());
613 dir_len += 1;
614 std::string obj = this->GetObjectFileNameWithoutTarget(*sf, dir_len);
615 if(!obj.empty())
617 std::string ofname = this->Makefile->GetCurrentOutputDirectory();
618 ofname += "/";
619 ofname += obj;
620 objVector.push_back(ofname);
621 this->AddCustomCommandToCreateObject(ofname.c_str(),
622 llang, *(*i), target);
623 objs += this->Convert(ofname.c_str(),START_OUTPUT,MAKEFILE);
624 objs += " ";
628 std::string createRule = "CMAKE_";
629 createRule += llang;
630 createRule += target.GetCreateRuleVariable();
631 std::string targetName = target.GetFullName();
632 // Executable :
633 // Shared Library:
634 // Static Library:
635 // Shared Module:
636 std::string linkLibs; // should be set
637 std::string flags; // should be set
638 std::string linkFlags; // should be set
639 this->GetTargetFlags(linkLibs, flags, linkFlags, target);
640 cmLocalGenerator::RuleVariables vars;
641 vars.Language = llang;
642 vars.Objects = objs.c_str();
643 vars.ObjectDir = ".";
644 vars.Target = targetName.c_str();
645 vars.LinkLibraries = linkLibs.c_str();
646 vars.Flags = flags.c_str();
647 vars.LinkFlags = linkFlags.c_str();
649 std::string langFlags;
650 this->AddLanguageFlags(langFlags, llang, 0);
651 vars.LanguageCompileFlags = langFlags.c_str();
653 cmCustomCommandLines commandLines;
654 std::vector<std::string> rules;
655 rules.push_back(this->Makefile->GetRequiredDefinition(createRule.c_str()));
656 std::vector<std::string> commands;
657 cmSystemTools::ExpandList(rules, commands);
658 for(std::vector<std::string>::iterator i = commands.begin();
659 i != commands.end(); ++i)
661 // Expand the full command line string.
662 this->ExpandRuleVariables(*i, vars);
663 // Parse the string to get the custom command line.
664 cmCustomCommandLine commandLine;
665 std::vector<cmStdString> cmd = cmSystemTools::ParseArguments(i->c_str());
666 for(std::vector<cmStdString>::iterator a = cmd.begin();
667 a != cmd.end(); ++a)
669 commandLine.push_back(*a);
672 // Store this command line.
673 commandLines.push_back(commandLine);
675 std::string targetFullPath = target.GetFullPath();
676 // Generate a meaningful comment for the command.
677 std::string comment = "Linking ";
678 comment += llang;
679 comment += " target ";
680 comment += this->Convert(targetFullPath.c_str(), START_OUTPUT);
681 this->Makefile->AddCustomCommandToOutput(
682 targetFullPath.c_str(),
683 objVector,
685 commandLines,
686 comment.c_str(),
687 this->Makefile->GetStartOutputDirectory()
689 target.AddSourceFile
690 (this->Makefile->GetSource(targetFullPath.c_str()));
694 void cmLocalGenerator
695 ::CreateCustomTargetsAndCommands(std::set<cmStdString> const& lang)
697 cmTargets &tgts = this->Makefile->GetTargets();
698 for(cmTargets::iterator l = tgts.begin();
699 l != tgts.end(); l++)
701 cmTarget& target = l->second;
702 switch(target.GetType())
704 case cmTarget::STATIC_LIBRARY:
705 case cmTarget::SHARED_LIBRARY:
706 case cmTarget::MODULE_LIBRARY:
707 case cmTarget::EXECUTABLE:
709 const char* llang =
710 target.GetLinkerLanguage(this->GetGlobalGenerator());
711 if(!llang)
713 cmSystemTools::Error
714 ("CMake can not determine linker language for target:",
715 target.GetName());
716 return;
718 // if the language is not in the set lang then create custom
719 // commands to build the target
720 if(lang.count(llang) == 0)
722 this->AddBuildTargetRule(llang, target);
725 break;
726 case cmTarget::UTILITY:
727 case cmTarget::GLOBAL_TARGET:
728 case cmTarget::INSTALL_FILES:
729 case cmTarget::INSTALL_PROGRAMS:
730 case cmTarget::INSTALL_DIRECTORY:
731 break;
736 // List of variables that are replaced when
737 // rules are expanced. These variables are
738 // replaced in the form <var> with GetSafeDefinition(var).
739 // ${LANG} is replaced in the variable first with all enabled
740 // languages.
741 static const char* ruleReplaceVars[] =
743 "CMAKE_${LANG}_COMPILER",
744 "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
745 "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
746 "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
747 "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
748 "CMAKE_${LANG}_LINK_FLAGS",
749 "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
750 "CMAKE_${LANG}_ARCHIVE",
751 "CMAKE_AR",
752 "CMAKE_CURRENT_SOURCE_DIR",
753 "CMAKE_CURRENT_BINARY_DIR",
754 "CMAKE_RANLIB",
755 "CMAKE_LINKER",
759 std::string
760 cmLocalGenerator::ExpandRuleVariable(std::string const& variable,
761 const RuleVariables& replaceValues)
763 if(replaceValues.LinkFlags)
765 if(variable == "LINK_FLAGS")
767 return replaceValues.LinkFlags;
770 if(replaceValues.Flags)
772 if(variable == "FLAGS")
774 return replaceValues.Flags;
778 if(replaceValues.Source)
780 if(variable == "SOURCE")
782 return replaceValues.Source;
785 if(replaceValues.PreprocessedSource)
787 if(variable == "PREPROCESSED_SOURCE")
789 return replaceValues.PreprocessedSource;
792 if(replaceValues.AssemblySource)
794 if(variable == "ASSEMBLY_SOURCE")
796 return replaceValues.AssemblySource;
799 if(replaceValues.Object)
801 if(variable == "OBJECT")
803 return replaceValues.Object;
806 if(replaceValues.ObjectDir)
808 if(variable == "OBJECT_DIR")
810 return replaceValues.ObjectDir;
813 if(replaceValues.Objects)
815 if(variable == "OBJECTS")
817 return replaceValues.Objects;
820 if(replaceValues.ObjectsQuoted)
822 if(variable == "OBJECTS_QUOTED")
824 return replaceValues.ObjectsQuoted;
827 if(replaceValues.Defines && variable == "DEFINES")
829 return replaceValues.Defines;
831 if(replaceValues.TargetPDB )
833 if(variable == "TARGET_PDB")
835 return replaceValues.TargetPDB;
839 if(replaceValues.Target)
841 if(variable == "TARGET_QUOTED")
843 std::string targetQuoted = replaceValues.Target;
844 if(targetQuoted.size() && targetQuoted[0] != '\"')
846 targetQuoted = '\"';
847 targetQuoted += replaceValues.Target;
848 targetQuoted += '\"';
850 return targetQuoted;
852 if(replaceValues.LanguageCompileFlags)
854 if(variable == "LANGUAGE_COMPILE_FLAGS")
856 return replaceValues.LanguageCompileFlags;
859 if(replaceValues.Target)
861 if(variable == "TARGET")
863 return replaceValues.Target;
866 if(variable == "TARGET_IMPLIB")
868 return this->TargetImplib;
870 if(variable == "TARGET_VERSION_MAJOR")
872 if(replaceValues.TargetVersionMajor)
874 return replaceValues.TargetVersionMajor;
876 else
878 return "0";
881 if(variable == "TARGET_VERSION_MINOR")
883 if(replaceValues.TargetVersionMinor)
885 return replaceValues.TargetVersionMinor;
887 else
889 return "0";
892 if(replaceValues.Target)
894 if(variable == "TARGET_BASE")
896 // Strip the last extension off the target name.
897 std::string targetBase = replaceValues.Target;
898 std::string::size_type pos = targetBase.rfind(".");
899 if(pos != targetBase.npos)
901 return targetBase.substr(0, pos);
903 else
905 return targetBase;
910 if(replaceValues.TargetSOName)
912 if(variable == "TARGET_SONAME")
914 if(replaceValues.Language)
916 std::string name = "CMAKE_SHARED_LIBRARY_SONAME_";
917 name += replaceValues.Language;
918 name += "_FLAG";
919 if(this->Makefile->GetDefinition(name.c_str()))
921 return replaceValues.TargetSOName;
924 return "";
927 if(replaceValues.TargetInstallNameDir)
929 if(variable == "TARGET_INSTALLNAME_DIR")
931 return replaceValues.TargetInstallNameDir;
934 if(replaceValues.LinkLibraries)
936 if(variable == "LINK_LIBRARIES")
938 return replaceValues.LinkLibraries;
941 if(variable == "CMAKE_COMMAND")
943 const char* cmcommand =
944 this->GlobalGenerator->GetCMakeInstance()->GetCMakeCommand();
945 return this->Convert(cmcommand, FULL, SHELL);
947 std::vector<std::string> enabledLanguages;
948 this->GlobalGenerator->GetEnabledLanguages(enabledLanguages);
949 // loop over language specific replace variables
950 int pos = 0;
951 while(ruleReplaceVars[pos])
953 for(std::vector<std::string>::iterator i = enabledLanguages.begin();
954 i != enabledLanguages.end(); ++i)
956 const char* lang = i->c_str();
957 std::string actualReplace = ruleReplaceVars[pos];
958 // If this is the compiler then look for the extra variable
959 // _COMPILER_ARG1 which must be the first argument to the compiler
960 const char* compilerArg1 = 0;
961 if(actualReplace == "CMAKE_${LANG}_COMPILER")
963 std::string arg1 = actualReplace + "_ARG1";
964 cmSystemTools::ReplaceString(arg1, "${LANG}", lang);
965 compilerArg1 = this->Makefile->GetDefinition(arg1.c_str());
967 if(actualReplace.find("${LANG}") != actualReplace.npos)
969 cmSystemTools::ReplaceString(actualReplace, "${LANG}", lang);
971 if(actualReplace == variable)
973 std::string replace =
974 this->Makefile->GetSafeDefinition(variable.c_str());
975 // if the variable is not a FLAG then treat it like a path
976 if(variable.find("_FLAG") == variable.npos)
978 std::string ret = this->ConvertToOutputForExisting(replace.c_str());
979 // if there is a required first argument to the compiler add it
980 // to the compiler string
981 if(compilerArg1)
983 ret += " ";
984 ret += compilerArg1;
986 return ret;
988 return replace;
991 pos++;
993 return variable;
997 void
998 cmLocalGenerator::ExpandRuleVariables(std::string& s,
999 const RuleVariables& replaceValues)
1001 std::vector<std::string> enabledLanguages;
1002 this->GlobalGenerator->GetEnabledLanguages(enabledLanguages);
1003 std::string::size_type start = s.find('<');
1004 // no variables to expand
1005 if(start == s.npos)
1007 return;
1009 std::string::size_type pos = 0;
1010 std::string expandedInput;
1011 while(start != s.npos && start < s.size()-2)
1013 std::string::size_type end = s.find('>', start);
1014 // if we find a < with no > we are done
1015 if(end == s.npos)
1017 return;
1019 char c = s[start+1];
1020 // if the next char after the < is not A-Za-z then
1021 // skip it and try to find the next < in the string
1022 if(!isalpha(c))
1024 start = s.find('<', start+1);
1026 else
1028 // extract the var
1029 std::string var = s.substr(start+1, end - start-1);
1030 std::string replace = this->ExpandRuleVariable(var,
1031 replaceValues);
1032 expandedInput += s.substr(pos, start-pos);
1033 expandedInput += replace;
1034 // move to next one
1035 start = s.find('<', start+var.size()+2);
1036 pos = end+1;
1039 // add the rest of the input
1040 expandedInput += s.substr(pos, s.size()-pos);
1041 s = expandedInput;
1045 std::string
1046 cmLocalGenerator::ConvertToOutputForExisting(const char* p)
1048 std::string ret = p;
1049 if(this->WindowsShell && ret.find(' ') != ret.npos
1050 && cmSystemTools::FileExists(p))
1052 if(cmSystemTools::GetShortPath(p, ret))
1054 return this->Convert(ret.c_str(), NONE, SHELL, true);
1057 return this->Convert(p, START_OUTPUT, SHELL, true);
1060 const char* cmLocalGenerator::GetIncludeFlags(const char* lang)
1062 if(!lang)
1064 return "";
1066 if(this->LanguageToIncludeFlags.count(lang))
1068 return this->LanguageToIncludeFlags[lang].c_str();
1070 cmOStringStream includeFlags;
1071 std::vector<std::string> includes;
1072 this->GetIncludeDirectories(includes);
1073 std::vector<std::string>::iterator i;
1075 std::string flagVar = "CMAKE_INCLUDE_FLAG_";
1076 flagVar += lang;
1077 const char* includeFlag =
1078 this->Makefile->GetSafeDefinition(flagVar.c_str());
1079 flagVar = "CMAKE_INCLUDE_FLAG_SEP_";
1080 flagVar += lang;
1081 const char* sep = this->Makefile->GetDefinition(flagVar.c_str());
1082 bool quotePaths = false;
1083 if(this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS"))
1085 quotePaths = true;
1087 bool repeatFlag = true;
1088 // should the include flag be repeated like ie. -IA -IB
1089 if(!sep)
1091 sep = " ";
1093 else
1095 // if there is a separator then the flag is not repeated but is only
1096 // given once i.e. -classpath a:b:c
1097 repeatFlag = false;
1100 // Support special system include flag if it is available and the
1101 // normal flag is repeated for each directory.
1102 std::string sysFlagVar = "CMAKE_INCLUDE_SYSTEM_FLAG_";
1103 sysFlagVar += lang;
1104 const char* sysIncludeFlag = 0;
1105 if(repeatFlag)
1107 sysIncludeFlag = this->Makefile->GetDefinition(sysFlagVar.c_str());
1110 bool flagUsed = false;
1111 std::set<cmStdString> emitted;
1112 #ifdef __APPLE__
1113 emitted.insert("/System/Library/Frameworks");
1114 #endif
1115 for(i = includes.begin(); i != includes.end(); ++i)
1117 #ifdef __APPLE__
1118 if(cmSystemTools::IsPathToFramework(i->c_str()))
1120 std::string frameworkDir = *i;
1121 frameworkDir += "/../";
1122 frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir.c_str());
1123 if(emitted.insert(frameworkDir).second)
1125 includeFlags
1126 << "-F"
1127 << this->ConvertToOutputForExisting(frameworkDir.c_str()) << " ";
1129 continue;
1131 #endif
1132 std::string include = *i;
1133 if(!flagUsed || repeatFlag)
1135 if(sysIncludeFlag &&
1136 this->Makefile->IsSystemIncludeDirectory(i->c_str()))
1138 includeFlags << sysIncludeFlag;
1140 else
1142 includeFlags << includeFlag;
1144 flagUsed = true;
1146 std::string includePath = this->ConvertToOutputForExisting(i->c_str());
1147 if(quotePaths && includePath.size() && includePath[0] != '\"')
1149 includeFlags << "\"";
1151 includeFlags << includePath;
1152 if(quotePaths && includePath.size() && includePath[0] != '\"')
1154 includeFlags << "\"";
1156 includeFlags << sep;
1158 std::string flags = includeFlags.str();
1159 // remove trailing separators
1160 if((sep[0] != ' ') && flags[flags.size()-1] == sep[0])
1162 flags[flags.size()-1] = ' ';
1164 std::string defineFlags = this->Makefile->GetDefineFlags();
1165 flags += defineFlags;
1166 this->LanguageToIncludeFlags[lang] = flags;
1168 // Use this temorary variable for the return value to work-around a
1169 // bogus GCC 2.95 warning.
1170 const char* ret = this->LanguageToIncludeFlags[lang].c_str();
1171 return ret;
1174 //----------------------------------------------------------------------------
1175 void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
1176 bool filter_system_dirs)
1178 // Need to decide whether to automatically include the source and
1179 // binary directories at the beginning of the include path.
1180 bool includeSourceDir = false;
1181 bool includeBinaryDir = false;
1183 // When automatic include directories are requested for a build then
1184 // include the source and binary directories at the beginning of the
1185 // include path to approximate include file behavior for an
1186 // in-source build. This does not account for the case of a source
1187 // file in a subdirectory of the current source directory but we
1188 // cannot fix this because not all native build tools support
1189 // per-source-file include paths.
1190 if(this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR"))
1192 includeSourceDir = true;
1193 includeBinaryDir = true;
1196 // CMake versions below 2.0 would add the source tree to the -I path
1197 // automatically. Preserve compatibility.
1198 const char* versionValue =
1199 this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY");
1200 int major = 0;
1201 int minor = 0;
1202 if(versionValue && sscanf(versionValue, "%d.%d", &major, &minor) != 2)
1204 versionValue = 0;
1206 if(versionValue && major < 2)
1208 includeSourceDir = true;
1211 // Hack for VTK 4.0 - 4.4 which depend on the old behavior but do
1212 // not set the backwards compatibility level automatically.
1213 const char* vtkSourceDir =
1214 this->Makefile->GetDefinition("VTK_SOURCE_DIR");
1215 if(vtkSourceDir)
1217 const char* vtk_major =
1218 this->Makefile->GetDefinition("VTK_MAJOR_VERSION");
1219 const char* vtk_minor =
1220 this->Makefile->GetDefinition("VTK_MINOR_VERSION");
1221 vtk_major = vtk_major? vtk_major : "4";
1222 vtk_minor = vtk_minor? vtk_minor : "4";
1223 int vmajor = 0;
1224 int vminor = 0;
1225 if(sscanf(vtk_major, "%d", &vmajor) &&
1226 sscanf(vtk_minor, "%d", &vminor) && vmajor == 4 && vminor <= 4)
1228 includeSourceDir = true;
1232 // Do not repeat an include path.
1233 std::set<cmStdString> emitted;
1235 // Store the automatic include paths.
1236 if(includeBinaryDir)
1238 dirs.push_back(this->Makefile->GetStartOutputDirectory());
1239 emitted.insert(this->Makefile->GetStartOutputDirectory());
1241 if(includeSourceDir)
1243 if(emitted.find(this->Makefile->GetStartDirectory()) == emitted.end())
1245 dirs.push_back(this->Makefile->GetStartDirectory());
1246 emitted.insert(this->Makefile->GetStartDirectory());
1250 if(filter_system_dirs)
1252 // Do not explicitly add the standard include path "/usr/include".
1253 // This can cause problems with certain standard library
1254 // implementations because the wrong headers may be found first.
1255 emitted.insert("/usr/include");
1256 if(const char* implicitIncludes = this->Makefile->GetDefinition
1257 ("CMAKE_PLATFORM_IMPLICIT_INCLUDE_DIRECTORIES"))
1259 std::vector<std::string> implicitIncludeVec;
1260 cmSystemTools::ExpandListArgument(implicitIncludes, implicitIncludeVec);
1261 for(unsigned int k = 0; k < implicitIncludeVec.size(); ++k)
1263 emitted.insert(implicitIncludeVec[k]);
1268 // Get the project-specified include directories.
1269 std::vector<std::string>& includes =
1270 this->Makefile->GetIncludeDirectories();
1272 // Support putting all the in-project include directories first if
1273 // it is requested by the project.
1274 if(this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE"))
1276 const char* topSourceDir = this->Makefile->GetHomeDirectory();
1277 const char* topBinaryDir = this->Makefile->GetHomeOutputDirectory();
1278 for(std::vector<std::string>::iterator i = includes.begin();
1279 i != includes.end(); ++i)
1281 // Emit this directory only if it is a subdirectory of the
1282 // top-level source or binary tree.
1283 if(cmSystemTools::ComparePath(i->c_str(), topSourceDir) ||
1284 cmSystemTools::ComparePath(i->c_str(), topBinaryDir) ||
1285 cmSystemTools::IsSubDirectory(i->c_str(), topSourceDir) ||
1286 cmSystemTools::IsSubDirectory(i->c_str(), topBinaryDir))
1288 if(emitted.insert(*i).second)
1290 dirs.push_back(*i);
1296 // Construct the final ordered include directory list.
1297 for(std::vector<std::string>::iterator i = includes.begin();
1298 i != includes.end(); ++i)
1300 if(emitted.insert(*i).second)
1302 dirs.push_back(*i);
1307 void cmLocalGenerator::GetTargetFlags(std::string& linkLibs,
1308 std::string& flags,
1309 std::string& linkFlags,
1310 cmTarget& target)
1312 std::string buildType =
1313 this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
1314 buildType = cmSystemTools::UpperCase(buildType);
1315 const char* libraryLinkVariable =
1316 "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
1318 switch(target.GetType())
1320 case cmTarget::STATIC_LIBRARY:
1322 const char* targetLinkFlags =
1323 target.GetProperty("STATIC_LIBRARY_FLAGS");
1324 if(targetLinkFlags)
1326 linkFlags += targetLinkFlags;
1327 linkFlags += " ";
1330 break;
1331 case cmTarget::MODULE_LIBRARY:
1332 libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
1333 case cmTarget::SHARED_LIBRARY:
1335 linkFlags = this->Makefile->GetSafeDefinition(libraryLinkVariable);
1336 linkFlags += " ";
1337 if(buildType.size())
1339 std::string build = libraryLinkVariable;
1340 build += "_";
1341 build += buildType;
1342 linkFlags += this->Makefile->GetSafeDefinition(build.c_str());
1343 linkFlags += " ";
1345 if(this->Makefile->IsOn("WIN32") &&
1346 !(this->Makefile->IsOn("CYGWIN") || this->Makefile->IsOn("MINGW")))
1348 const std::vector<cmSourceFile*>& sources = target.GetSourceFiles();
1349 for(std::vector<cmSourceFile*>::const_iterator i = sources.begin();
1350 i != sources.end(); ++i)
1352 cmSourceFile* sf = *i;
1353 if(sf->GetExtension() == "def")
1355 linkFlags +=
1356 this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
1357 linkFlags += this->Convert(sf->GetFullPath().c_str(),
1358 START_OUTPUT, SHELL);
1359 linkFlags += " ";
1363 const char* targetLinkFlags = target.GetProperty("LINK_FLAGS");
1364 if(targetLinkFlags)
1366 linkFlags += targetLinkFlags;
1367 linkFlags += " ";
1368 std::string configLinkFlags = targetLinkFlags;
1369 configLinkFlags += buildType;
1370 targetLinkFlags = target.GetProperty(configLinkFlags.c_str());
1371 if(targetLinkFlags)
1373 linkFlags += targetLinkFlags;
1374 linkFlags += " ";
1377 cmOStringStream linklibsStr;
1378 this->OutputLinkLibraries(linklibsStr, target, false);
1379 linkLibs = linklibsStr.str();
1381 break;
1382 case cmTarget::EXECUTABLE:
1384 linkFlags +=
1385 this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
1386 linkFlags += " ";
1387 if(buildType.size())
1389 std::string build = "CMAKE_EXE_LINKER_FLAGS_";
1390 build += buildType;
1391 linkFlags += this->Makefile->GetSafeDefinition(build.c_str());
1392 linkFlags += " ";
1394 const char* linkLanguage =
1395 target.GetLinkerLanguage(this->GetGlobalGenerator());
1396 if(!linkLanguage)
1398 cmSystemTools::Error
1399 ("CMake can not determine linker language for target:",
1400 target.GetName());
1401 return;
1403 std::string langVar = "CMAKE_";
1404 langVar += linkLanguage;
1405 std::string flagsVar = langVar + "_FLAGS";
1406 std::string sharedFlagsVar = "CMAKE_SHARED_LIBRARY_";
1407 sharedFlagsVar += linkLanguage;
1408 sharedFlagsVar += "_FLAGS";
1409 flags += this->Makefile->GetSafeDefinition(flagsVar.c_str());
1410 flags += " ";
1411 flags += this->Makefile->GetSafeDefinition(sharedFlagsVar.c_str());
1412 flags += " ";
1413 cmOStringStream linklibs;
1414 this->OutputLinkLibraries(linklibs, target, false);
1415 linkLibs = linklibs.str();
1416 if(cmSystemTools::IsOn
1417 (this->Makefile->GetDefinition("BUILD_SHARED_LIBS")))
1419 std::string sFlagVar = std::string("CMAKE_SHARED_BUILD_")
1420 + linkLanguage + std::string("_FLAGS");
1421 linkFlags += this->Makefile->GetSafeDefinition(sFlagVar.c_str());
1422 linkFlags += " ";
1424 if ( target.GetPropertyAsBool("WIN32_EXECUTABLE") )
1426 linkFlags +=
1427 this->Makefile->GetSafeDefinition("CMAKE_CREATE_WIN32_EXE");
1428 linkFlags += " ";
1430 else
1432 linkFlags +=
1433 this->Makefile->GetSafeDefinition("CMAKE_CREATE_CONSOLE_EXE");
1434 linkFlags += " ";
1436 const char* targetLinkFlags = target.GetProperty("LINK_FLAGS");
1437 if(targetLinkFlags)
1439 linkFlags += targetLinkFlags;
1440 linkFlags += " ";
1441 std::string configLinkFlags = targetLinkFlags;
1442 configLinkFlags += buildType;
1443 targetLinkFlags = target.GetProperty(configLinkFlags.c_str());
1444 if(targetLinkFlags)
1446 linkFlags += targetLinkFlags;
1447 linkFlags += " ";
1451 break;
1452 case cmTarget::UTILITY:
1453 case cmTarget::GLOBAL_TARGET:
1454 case cmTarget::INSTALL_FILES:
1455 case cmTarget::INSTALL_PROGRAMS:
1456 case cmTarget::INSTALL_DIRECTORY:
1457 break;
1461 std::string cmLocalGenerator::ConvertToLinkReference(std::string const& lib)
1463 #if defined(_WIN32) && !defined(__CYGWIN__)
1464 // Work-ardound command line parsing limitations in MSVC 6.0 and
1465 // Watcom.
1466 if(this->Makefile->IsOn("MSVC60") || this->Makefile->IsOn("WATCOM"))
1468 // Search for the last space.
1469 std::string::size_type pos = lib.rfind(' ');
1470 if(pos != lib.npos)
1472 // Find the slash after the last space, if any.
1473 pos = lib.find('/', pos);
1475 // Convert the portion of the path with a space to a short path.
1476 std::string sp;
1477 if(cmSystemTools::GetShortPath(lib.substr(0, pos).c_str(), sp))
1479 // Append the rest of the path with no space.
1480 sp += lib.substr(pos);
1482 // Convert to an output path.
1483 return this->Convert(sp.c_str(), NONE, SHELL);
1487 #endif
1489 // Normal behavior.
1490 return this->Convert(lib.c_str(), START_OUTPUT, SHELL);
1494 * Output the linking rules on a command line. For executables,
1495 * targetLibrary should be a NULL pointer. For libraries, it should point
1496 * to the name of the library. This will not link a library against itself.
1498 void cmLocalGenerator::OutputLinkLibraries(std::ostream& fout,
1499 cmTarget& tgt,
1500 bool relink)
1502 const char* config = this->Makefile->GetDefinition("CMAKE_BUILD_TYPE");
1503 cmComputeLinkInformation* pcli = tgt.GetLinkInformation(config);
1504 if(!pcli)
1506 return;
1508 cmComputeLinkInformation& cli = *pcli;
1510 // Collect library linking flags command line options.
1511 std::string linkLibs;
1513 const char* linkLanguage = cli.GetLinkLanguage();
1515 std::string libPathFlag =
1516 this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
1517 std::string libPathTerminator =
1518 this->Makefile->GetSafeDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
1520 // Flags to link an executable to shared libraries.
1521 std::string linkFlagsVar = "CMAKE_SHARED_LIBRARY_LINK_";
1522 linkFlagsVar += linkLanguage;
1523 linkFlagsVar += "_FLAGS";
1524 if( tgt.GetType() == cmTarget::EXECUTABLE )
1526 linkLibs = this->Makefile->GetSafeDefinition(linkFlagsVar.c_str());
1527 linkLibs += " ";
1530 // Append the framework search path flags.
1531 std::vector<std::string> const& fwDirs = cli.GetFrameworkPaths();
1532 for(std::vector<std::string>::const_iterator fdi = fwDirs.begin();
1533 fdi != fwDirs.end(); ++fdi)
1535 linkLibs += "-F";
1536 linkLibs += this->Convert(fdi->c_str(), NONE, SHELL, false);
1537 linkLibs += " ";
1540 // Append the library search path flags.
1541 std::vector<std::string> const& libDirs = cli.GetDirectories();
1542 for(std::vector<std::string>::const_iterator libDir = libDirs.begin();
1543 libDir != libDirs.end(); ++libDir)
1545 std::string libpath = this->ConvertToOutputForExisting(libDir->c_str());
1546 linkLibs += libPathFlag;
1547 linkLibs += libpath;
1548 linkLibs += libPathTerminator;
1549 linkLibs += " ";
1552 // Append the link items.
1553 typedef cmComputeLinkInformation::ItemVector ItemVector;
1554 ItemVector const& items = cli.GetItems();
1555 for(ItemVector::const_iterator li = items.begin(); li != items.end(); ++li)
1557 if(li->IsPath)
1559 linkLibs += this->ConvertToLinkReference(li->Value);
1561 else
1563 linkLibs += li->Value;
1565 linkLibs += " ";
1568 // Write the library flags to the build rule.
1569 fout << linkLibs;
1571 // Get the RPATH entries.
1572 std::vector<std::string> runtimeDirs;
1573 cli.GetRPath(runtimeDirs, relink);
1575 // Check what kind of rpath flags to use.
1576 if(cli.GetRuntimeSep().empty())
1578 // Each rpath entry gets its own option ("-R a -R b -R c")
1579 std::string rpath;
1580 for(std::vector<std::string>::iterator ri = runtimeDirs.begin();
1581 ri != runtimeDirs.end(); ++ri)
1583 rpath += cli.GetRuntimeFlag();
1584 rpath += this->Convert(ri->c_str(), FULL, SHELL, false);
1585 rpath += " ";
1587 fout << rpath;
1589 else
1591 // All rpath entries are combined ("-Wl,-rpath,a:b:c").
1592 std::string rpath = cli.GetRPathString(relink);
1594 // If not relinking, make sure the rpath string is long enough to
1595 // support a subsequent chrpath on installation.
1596 if(!relink)
1598 std::string::size_type minLength = cli.GetChrpathString().size();
1599 while(rpath.size() < minLength)
1601 rpath += cli.GetRuntimeSep();
1605 // Store the rpath option in the stream.
1606 if(!rpath.empty())
1608 fout << cli.GetRuntimeFlag();
1609 fout << this->EscapeForShell(rpath.c_str(), true);
1610 fout << " ";
1614 // Add the linker runtime search path if any.
1615 std::string rpath_link = cli.GetRPathLinkString();
1616 if(!cli.GetRPathLinkFlag().empty() && !rpath_link.empty())
1618 fout << cli.GetRPathLinkFlag();
1619 fout << this->EscapeForShell(rpath_link.c_str(), true);
1620 fout << " ";
1623 // Add standard libraries for this language.
1624 std::string standardLibsVar = "CMAKE_";
1625 standardLibsVar += cli.GetLinkLanguage();
1626 standardLibsVar += "_STANDARD_LIBRARIES";
1627 if(const char* stdLibs =
1628 this->Makefile->GetDefinition(standardLibsVar.c_str()))
1630 fout << stdLibs << " ";
1634 //----------------------------------------------------------------------------
1635 void cmLocalGenerator::AddLanguageFlags(std::string& flags,
1636 const char* lang,
1637 const char* config)
1639 // Add language-specific flags.
1640 std::string flagsVar = "CMAKE_";
1641 flagsVar += lang;
1642 flagsVar += "_FLAGS";
1643 if(this->EmitUniversalBinaryFlags)
1645 const char* osxArch =
1646 this->Makefile->GetDefinition("CMAKE_OSX_ARCHITECTURES");
1647 const char* sysroot =
1648 this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
1649 if(osxArch && sysroot && lang && lang[0] =='C')
1651 std::vector<std::string> archs;
1652 cmSystemTools::ExpandListArgument(std::string(osxArch),
1653 archs);
1654 bool addArchFlag = true;
1655 if(archs.size() == 1)
1657 const char* archOrig =
1658 this->Makefile->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES_DEFAULT");
1659 if(archs[0] == archOrig)
1661 addArchFlag = false;
1664 // if there is more than one arch add the -arch and
1665 // -isysroot flags, or if there is one arch flag, but
1666 // it is not the default -arch flag for the system, then
1667 // add it. Otherwize do not add -arch and -isysroot
1668 if(addArchFlag)
1670 for( std::vector<std::string>::iterator i = archs.begin();
1671 i != archs.end(); ++i)
1673 flags += " -arch ";
1674 flags += *i;
1676 flags += " -isysroot ";
1677 flags += sysroot;
1681 this->AddConfigVariableFlags(flags, flagsVar.c_str(), config);
1684 //----------------------------------------------------------------------------
1685 std::string cmLocalGenerator::GetRealDependency(const char* inName,
1686 const char* config)
1688 // Older CMake code may specify the dependency using the target
1689 // output file rather than the target name. Such code would have
1690 // been written before there was support for target properties that
1691 // modify the name so stripping down to just the file name should
1692 // produce the target name in this case.
1693 std::string name = cmSystemTools::GetFilenameName(inName);
1694 if(cmSystemTools::GetFilenameLastExtension(name) == ".exe")
1696 name = cmSystemTools::GetFilenameWithoutLastExtension(name);
1699 // Look for a CMake target with the given name.
1700 if(cmTarget* target = this->Makefile->FindTargetToUse(name.c_str()))
1702 // make sure it is not just a coincidence that the target name
1703 // found is part of the inName
1704 if(cmSystemTools::FileIsFullPath(inName))
1706 std::string tLocation = target->GetLocation(config);
1707 tLocation = cmSystemTools::GetFilenamePath(tLocation);
1708 std::string depLocation = cmSystemTools::GetFilenamePath(
1709 std::string(inName));
1710 depLocation = cmSystemTools::CollapseFullPath(depLocation.c_str());
1711 tLocation = cmSystemTools::CollapseFullPath(tLocation.c_str());
1712 if(depLocation != tLocation)
1714 // it is a full path to a depend that has the same name
1715 // as a target but is in a different location so do not use
1716 // the target as the depend
1717 return inName;
1720 switch (target->GetType())
1722 case cmTarget::EXECUTABLE:
1723 case cmTarget::STATIC_LIBRARY:
1724 case cmTarget::SHARED_LIBRARY:
1725 case cmTarget::MODULE_LIBRARY:
1727 // Get the location of the target's output file and depend on it.
1728 if(const char* location = target->GetLocation(config))
1730 return location;
1733 break;
1734 case cmTarget::UTILITY:
1735 case cmTarget::GLOBAL_TARGET:
1736 // Depending on a utility target may not work but just trust
1737 // the user to have given a valid name.
1738 return inName;
1739 case cmTarget::INSTALL_FILES:
1740 case cmTarget::INSTALL_PROGRAMS:
1741 case cmTarget::INSTALL_DIRECTORY:
1742 break;
1746 // The name was not that of a CMake target. It must name a file.
1747 if(cmSystemTools::FileIsFullPath(inName))
1749 // This is a full path. Return it as given.
1750 return inName;
1752 // Treat the name as relative to the source directory in which it
1753 // was given.
1754 name = this->Makefile->GetCurrentDirectory();
1755 name += "/";
1756 name += inName;
1757 return name;
1760 //----------------------------------------------------------------------------
1761 std::string cmLocalGenerator::GetRealLocation(const char* inName,
1762 const char* config)
1764 std::string outName=inName;
1765 // Look for a CMake target with the given name, which is an executable
1766 // and which can be run
1767 cmTarget* target = this->Makefile->FindTargetToUse(inName);
1768 if ((target != 0)
1769 && (target->GetType() == cmTarget::EXECUTABLE)
1770 && ((this->Makefile->IsOn("CMAKE_CROSSCOMPILING") == false)
1771 || (target->IsImported() == true)))
1773 outName = target->GetLocation( config );
1775 return outName;
1778 //----------------------------------------------------------------------------
1779 void cmLocalGenerator::AddSharedFlags(std::string& flags,
1780 const char* lang,
1781 bool shared)
1783 std::string flagsVar;
1785 // Add flags for dealing with shared libraries for this language.
1786 if(shared)
1788 flagsVar = "CMAKE_SHARED_LIBRARY_";
1789 flagsVar += lang;
1790 flagsVar += "_FLAGS";
1791 this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar.c_str()));
1794 // Add flags specific to shared builds.
1795 if(cmSystemTools::IsOn(this->Makefile->GetDefinition("BUILD_SHARED_LIBS")))
1797 flagsVar = "CMAKE_SHARED_BUILD_";
1798 flagsVar += lang;
1799 flagsVar += "_FLAGS";
1800 this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar.c_str()));
1804 //----------------------------------------------------------------------------
1805 void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
1806 const char* var,
1807 const char* config)
1809 // Add the flags from the variable itself.
1810 std::string flagsVar = var;
1811 this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar.c_str()));
1812 // Add the flags from the build-type specific variable.
1813 if(config && *config)
1815 flagsVar += "_";
1816 flagsVar += cmSystemTools::UpperCase(config);
1817 this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar.c_str()));
1821 //----------------------------------------------------------------------------
1822 void cmLocalGenerator::AppendFlags(std::string& flags,
1823 const char* newFlags)
1825 if(newFlags && *newFlags)
1827 std::string newf = newFlags;
1828 if(flags.size())
1830 flags += " ";
1832 flags += newFlags;
1836 //----------------------------------------------------------------------------
1837 void cmLocalGenerator::AppendDefines(std::string& defines,
1838 const char* defines_list,
1839 const char* lang)
1841 // Short-circuit if there are no definitions.
1842 if(!defines_list)
1844 return;
1847 // Expand the list of definitions.
1848 std::vector<std::string> defines_vec;
1849 cmSystemTools::ExpandListArgument(defines_list, defines_vec);
1851 // Short-circuit if there are no definitions.
1852 if(defines_vec.empty())
1854 return;
1857 // Lookup the define flag for the current language.
1858 std::string dflag = "-D";
1859 if(lang)
1861 std::string defineFlagVar = "CMAKE_";
1862 defineFlagVar += lang;
1863 defineFlagVar += "_DEFINE_FLAG";
1864 const char* df = this->Makefile->GetDefinition(defineFlagVar.c_str());
1865 if(df && *df)
1867 dflag = df;
1871 // Add each definition to the command line with appropriate escapes.
1872 const char* dsep = defines.empty()? "" : " ";
1873 for(std::vector<std::string>::const_iterator di = defines_vec.begin();
1874 di != defines_vec.end(); ++di)
1876 // Skip unsupported definitions.
1877 if(!this->CheckDefinition(*di))
1879 continue;
1882 // Separate from previous definitions.
1883 defines += dsep;
1884 dsep = " ";
1886 // Append the definition with proper escaping.
1887 defines += dflag;
1888 if(this->WatcomWMake)
1890 // The Watcom compiler does its own command line parsing instead
1891 // of using the windows shell rules. Definitions are one of
1892 // -DNAME
1893 // -DNAME=<cpp-token>
1894 // -DNAME="c-string with spaces and other characters(?@#$)"
1896 // Watcom will properly parse each of these cases from the
1897 // command line without any escapes. However we still have to
1898 // get the '$' and '#' characters through WMake as '$$' and
1899 // '$#'.
1900 for(const char* c = di->c_str(); *c; ++c)
1902 if(*c == '$' || *c == '#')
1904 defines += '$';
1906 defines += *c;
1909 else
1911 // Make the definition appear properly on the command line.
1912 defines += this->EscapeForShell(di->c_str(), true);
1917 //----------------------------------------------------------------------------
1918 std::string
1919 cmLocalGenerator::ConstructComment(const cmCustomCommand& cc,
1920 const char* default_comment)
1922 // Check for a comment provided with the command.
1923 if(cc.GetComment())
1925 return cc.GetComment();
1928 // Construct a reasonable default comment if possible.
1929 if(!cc.GetOutputs().empty())
1931 std::string comment;
1932 comment = "Generating ";
1933 const char* sep = "";
1934 for(std::vector<std::string>::const_iterator o = cc.GetOutputs().begin();
1935 o != cc.GetOutputs().end(); ++o)
1937 comment += sep;
1938 comment += this->Convert(o->c_str(), cmLocalGenerator::START_OUTPUT);
1939 sep = ", ";
1941 return comment;
1944 // Otherwise use the provided default.
1945 return default_comment;
1948 //----------------------------------------------------------------------------
1949 std::string
1950 cmLocalGenerator::ConvertToOptionallyRelativeOutputPath(const char* remote)
1952 return this->Convert(remote, START_OUTPUT, SHELL, true);
1955 //----------------------------------------------------------------------------
1956 std::string cmLocalGenerator::Convert(const char* source,
1957 RelativeRoot relative,
1958 OutputFormat output,
1959 bool optional)
1961 // Make sure the relative path conversion components are set.
1962 if(!this->PathConversionsSetup)
1964 this->SetupPathConversions();
1965 this->PathConversionsSetup = true;
1968 // Convert the path to a relative path.
1969 std::string result = source;
1971 if (!optional || this->UseRelativePaths)
1973 switch (relative)
1975 case HOME:
1976 //result = cmSystemTools::CollapseFullPath(result.c_str());
1977 result = this->ConvertToRelativePath(this->HomeDirectoryComponents,
1978 result.c_str());
1979 break;
1980 case START:
1981 //result = cmSystemTools::CollapseFullPath(result.c_str());
1982 result = this->ConvertToRelativePath(this->StartDirectoryComponents,
1983 result.c_str());
1984 break;
1985 case HOME_OUTPUT:
1986 //result = cmSystemTools::CollapseFullPath(result.c_str());
1987 result =
1988 this->ConvertToRelativePath(this->HomeOutputDirectoryComponents,
1989 result.c_str());
1990 break;
1991 case START_OUTPUT:
1992 //result = cmSystemTools::CollapseFullPath(result.c_str());
1993 result =
1994 this->ConvertToRelativePath(this->StartOutputDirectoryComponents,
1995 result.c_str());
1996 break;
1997 case FULL:
1998 result = cmSystemTools::CollapseFullPath(result.c_str());
1999 break;
2000 case NONE:
2001 break;
2004 // Now convert it to an output path.
2005 if (output == MAKEFILE)
2007 result = cmSystemTools::ConvertToOutputPath(result.c_str());
2009 else if( output == SHELL)
2011 // For the MSYS shell convert drive letters to posix paths, so
2012 // that c:/some/path becomes /c/some/path. This is needed to
2013 // avoid problems with the shell path translation.
2014 if(this->MSYSShell && !this->LinkScriptShell)
2016 if(result.size() > 2 && result[1] == ':')
2018 result[1] = result[0];
2019 result[0] = '/';
2022 if(this->WindowsShell)
2024 std::string::size_type pos = 0;
2025 while((pos = result.find('/', pos)) != std::string::npos)
2027 result[pos] = '\\';
2028 pos++;
2031 result = this->EscapeForShell(result.c_str(), true, false);
2033 return result;
2036 //----------------------------------------------------------------------------
2037 std::string cmLocalGenerator::FindRelativePathTopSource()
2039 // Relative path conversion within a single tree managed by CMake is
2040 // safe. We can use our parent relative path top if and only if
2041 // this is a subdirectory of that top.
2042 if(cmLocalGenerator* parent = this->GetParent())
2044 std::string parentTop = parent->FindRelativePathTopSource();
2045 if(cmSystemTools::IsSubDirectory(
2046 this->Makefile->GetStartDirectory(), parentTop.c_str()))
2048 return parentTop;
2052 // Otherwise this directory itself is the new top.
2053 return this->Makefile->GetStartDirectory();
2056 //----------------------------------------------------------------------------
2057 std::string cmLocalGenerator::FindRelativePathTopBinary()
2059 // Relative path conversion within a single tree managed by CMake is
2060 // safe. We can use our parent relative path top if and only if
2061 // this is a subdirectory of that top.
2062 if(cmLocalGenerator* parent = this->GetParent())
2064 std::string parentTop = parent->FindRelativePathTopBinary();
2065 if(cmSystemTools::IsSubDirectory(
2066 this->Makefile->GetStartOutputDirectory(), parentTop.c_str()))
2068 return parentTop;
2072 // Otherwise this directory itself is the new top.
2073 return this->Makefile->GetStartOutputDirectory();
2076 //----------------------------------------------------------------------------
2077 void cmLocalGenerator::ConfigureRelativePaths()
2079 // Relative path conversion inside the source tree is not used to
2080 // construct relative paths passed to build tools so it is safe to
2081 // even when the source is a network path.
2082 std::string source = this->FindRelativePathTopSource();
2083 this->RelativePathTopSource = source;
2085 // The current working directory on Windows cannot be a network
2086 // path. Therefore relative paths cannot work when the binary tree
2087 // is a network path.
2088 std::string binary = this->FindRelativePathTopBinary();
2089 if(binary.size() < 2 || binary.substr(0, 2) != "//")
2091 this->RelativePathTopBinary = binary;
2093 else
2095 this->RelativePathTopBinary = "";
2099 //----------------------------------------------------------------------------
2100 static bool cmLocalGeneratorNotAbove(const char* a, const char* b)
2102 return (cmSystemTools::ComparePath(a, b) ||
2103 cmSystemTools::IsSubDirectory(a, b));
2106 //----------------------------------------------------------------------------
2107 std::string
2108 cmLocalGenerator::ConvertToRelativePath(const std::vector<std::string>& local,
2109 const char* in_remote)
2111 // The path should never be quoted.
2112 assert(in_remote[0] != '\"');
2114 // The local path should never have a trailing slash.
2115 assert(local.size() > 0 && !(local[local.size()-1] == ""));
2117 // If the path is already relative then just return the path.
2118 if(!cmSystemTools::FileIsFullPath(in_remote))
2120 return in_remote;
2123 // Make sure relative path conversion is configured.
2124 if(!this->RelativePathsConfigured)
2126 this->ConfigureRelativePaths();
2127 this->RelativePathsConfigured = true;
2130 // Skip conversion if the path and local are not both in the source
2131 // or both in the binary tree.
2132 std::string local_path = cmSystemTools::JoinPath(local);
2133 if(!((cmLocalGeneratorNotAbove(local_path.c_str(),
2134 this->RelativePathTopBinary.c_str()) &&
2135 cmLocalGeneratorNotAbove(in_remote,
2136 this->RelativePathTopBinary.c_str())) ||
2137 (cmLocalGeneratorNotAbove(local_path.c_str(),
2138 this->RelativePathTopSource.c_str()) &&
2139 cmLocalGeneratorNotAbove(in_remote,
2140 this->RelativePathTopSource.c_str()))))
2142 return in_remote;
2145 // Identify the longest shared path component between the remote
2146 // path and the local path.
2147 std::vector<std::string> remote;
2148 cmSystemTools::SplitPath(in_remote, remote);
2149 unsigned int common=0;
2150 while(common < remote.size() &&
2151 common < local.size() &&
2152 cmSystemTools::ComparePath(remote[common].c_str(),
2153 local[common].c_str()))
2155 ++common;
2158 // If no part of the path is in common then return the full path.
2159 if(common == 0)
2161 return in_remote;
2164 // If the entire path is in common then just return a ".".
2165 if(common == remote.size() &&
2166 common == local.size())
2168 return ".";
2171 // If the entire path is in common except for a trailing slash then
2172 // just return a "./".
2173 if(common+1 == remote.size() &&
2174 remote[common].size() == 0 &&
2175 common == local.size())
2177 return "./";
2180 // Construct the relative path.
2181 std::string relative;
2183 // First add enough ../ to get up to the level of the shared portion
2184 // of the path. Leave off the trailing slash. Note that the last
2185 // component of local will never be empty because local should never
2186 // have a trailing slash.
2187 for(unsigned int i=common; i < local.size(); ++i)
2189 relative += "..";
2190 if(i < local.size()-1)
2192 relative += "/";
2196 // Now add the portion of the destination path that is not included
2197 // in the shared portion of the path. Add a slash the first time
2198 // only if there was already something in the path. If there was a
2199 // trailing slash in the input then the last iteration of the loop
2200 // will add a slash followed by an empty string which will preserve
2201 // the trailing slash in the output.
2202 for(unsigned int i=common; i < remote.size(); ++i)
2204 if(relative.size() > 0)
2206 relative += "/";
2208 relative += remote[i];
2211 // Finally return the path.
2212 return relative;
2215 //----------------------------------------------------------------------------
2216 void
2217 cmLocalGenerator
2218 ::GenerateTargetInstallRules(
2219 std::ostream& os, const char* config,
2220 std::vector<std::string> const& configurationTypes)
2222 // Convert the old-style install specification from each target to
2223 // an install generator and run it.
2224 cmTargets& tgts = this->Makefile->GetTargets();
2225 for(cmTargets::iterator l = tgts.begin(); l != tgts.end(); ++l)
2227 // Include the user-specified pre-install script for this target.
2228 if(const char* preinstall = l->second.GetProperty("PRE_INSTALL_SCRIPT"))
2230 cmInstallScriptGenerator g(preinstall, false, 0);
2231 g.Generate(os, config, configurationTypes);
2234 // Install this target if a destination is given.
2235 if(l->second.GetInstallPath() != "")
2237 // Compute the full install destination. Note that converting
2238 // to unix slashes also removes any trailing slash.
2239 // We also skip over the leading slash given by the user.
2240 std::string destination = l->second.GetInstallPath().substr(1);
2241 cmSystemTools::ConvertToUnixSlashes(destination);
2243 // Generate the proper install generator for this target type.
2244 switch(l->second.GetType())
2246 case cmTarget::EXECUTABLE:
2247 case cmTarget::STATIC_LIBRARY:
2248 case cmTarget::MODULE_LIBRARY:
2250 // Use a target install generator.
2251 cmInstallTargetGenerator g(l->second, destination.c_str(), false);
2252 g.Generate(os, config, configurationTypes);
2254 break;
2255 case cmTarget::SHARED_LIBRARY:
2257 #if defined(_WIN32) || defined(__CYGWIN__)
2258 // Special code to handle DLL. Install the import library
2259 // to the normal destination and the DLL to the runtime
2260 // destination.
2261 cmInstallTargetGenerator g1(l->second, destination.c_str(), true);
2262 g1.Generate(os, config, configurationTypes);
2263 // We also skip over the leading slash given by the user.
2264 destination = l->second.GetRuntimeInstallPath().substr(1);
2265 cmSystemTools::ConvertToUnixSlashes(destination);
2266 cmInstallTargetGenerator g2(l->second, destination.c_str(), false);
2267 g2.Generate(os, config, configurationTypes);
2268 #else
2269 // Use a target install generator.
2270 cmInstallTargetGenerator g(l->second, destination.c_str(), false);
2271 g.Generate(os, config, configurationTypes);
2272 #endif
2274 break;
2275 default:
2276 break;
2280 // Include the user-specified post-install script for this target.
2281 if(const char* postinstall = l->second.GetProperty("POST_INSTALL_SCRIPT"))
2283 cmInstallScriptGenerator g(postinstall, false, 0);
2284 g.Generate(os, config, configurationTypes);
2289 #if defined(CM_LG_ENCODE_OBJECT_NAMES)
2290 static std::string cmLocalGeneratorMD5(const char* input)
2292 char md5out[32];
2293 cmsysMD5* md5 = cmsysMD5_New();
2294 cmsysMD5_Initialize(md5);
2295 cmsysMD5_Append(md5, reinterpret_cast<unsigned char const*>(input), -1);
2296 cmsysMD5_FinalizeHex(md5, md5out);
2297 cmsysMD5_Delete(md5);
2298 return std::string(md5out, 32);
2301 static bool
2302 cmLocalGeneratorShortenObjectName(std::string& objName,
2303 std::string::size_type max_len)
2305 // Replace the beginning of the path portion of the object name with
2306 // its own md5 sum.
2307 std::string::size_type pos = objName.find('/', objName.size()-max_len+32);
2308 if(pos != objName.npos)
2310 std::string md5name = cmLocalGeneratorMD5(objName.substr(0, pos).c_str());
2311 md5name += objName.substr(pos);
2312 objName = md5name;
2314 // The object name is now short enough.
2315 return true;
2317 else
2319 // The object name could not be shortened enough.
2320 return false;
2324 static bool cmLocalGeneratorCheckObjectName(std::string& objName,
2325 std::string::size_type dir_len)
2327 // Choose a maximum file name length.
2328 #if defined(_WIN32) || defined(__CYGWIN__)
2329 std::string::size_type const max_total_len = 250;
2330 #else
2331 std::string::size_type const max_total_len = 1000;
2332 #endif
2334 // Enforce the maximum file name length if possible.
2335 std::string::size_type max_obj_len = max_total_len;
2336 if(dir_len < max_total_len)
2338 max_obj_len = max_total_len - dir_len;
2339 if(objName.size() > max_obj_len)
2341 // The current object file name is too long. Try to shorten it.
2342 return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
2344 else
2346 // The object file name is short enough.
2347 return true;
2350 else
2352 // The build directory in which the object will be stored is
2353 // already too deep.
2354 return false;
2357 #endif
2359 //----------------------------------------------------------------------------
2360 std::string&
2361 cmLocalGenerator
2362 ::CreateSafeUniqueObjectFileName(const char* sin,
2363 std::string::size_type dir_len)
2365 // Look for an existing mapped name for this object file.
2366 std::map<cmStdString,cmStdString>::iterator it =
2367 this->UniqueObjectNamesMap.find(sin);
2369 // If no entry exists create one.
2370 if(it == this->UniqueObjectNamesMap.end())
2372 // Start with the original name.
2373 std::string ssin = sin;
2375 // Avoid full paths by removing leading slashes.
2376 std::string::size_type pos = 0;
2377 for(;pos < ssin.size() && ssin[pos] == '/'; ++pos);
2378 ssin = ssin.substr(pos);
2380 // Avoid full paths by removing colons.
2381 cmSystemTools::ReplaceString(ssin, ":", "_");
2383 // Avoid relative paths that go up the tree.
2384 cmSystemTools::ReplaceString(ssin, "../", "__/");
2386 // Avoid spaces.
2387 cmSystemTools::ReplaceString(ssin, " ", "_");
2389 // Mangle the name if necessary.
2390 if(this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES"))
2392 bool done;
2393 int cc = 0;
2394 char rpstr[100];
2395 sprintf(rpstr, "_p_");
2396 cmSystemTools::ReplaceString(ssin, "+", rpstr);
2397 std::string sssin = sin;
2400 done = true;
2401 for ( it = this->UniqueObjectNamesMap.begin();
2402 it != this->UniqueObjectNamesMap.end();
2403 ++ it )
2405 if ( it->second == ssin )
2407 done = false;
2410 if ( done )
2412 break;
2414 sssin = ssin;
2415 cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
2416 sprintf(rpstr, "_p%d_", cc++);
2418 while ( !done );
2421 #if defined(CM_LG_ENCODE_OBJECT_NAMES)
2422 cmLocalGeneratorCheckObjectName(ssin, dir_len);
2423 #else
2424 (void)dir_len;
2425 #endif
2427 // Insert the newly mapped object file name.
2428 std::map<cmStdString, cmStdString>::value_type e(sin, ssin);
2429 it = this->UniqueObjectNamesMap.insert(e).first;
2432 // Return the map entry.
2433 return it->second;
2436 //----------------------------------------------------------------------------
2437 std::string
2438 cmLocalGenerator
2439 ::GetObjectFileNameWithoutTarget(const cmSourceFile& source,
2440 std::string::size_type dir_len,
2441 bool* hasSourceExtension)
2443 // Construct the object file name using the full path to the source
2444 // file which is its only unique identification.
2445 const char* fullPath = source.GetFullPath().c_str();
2447 // Try referencing the source relative to the source tree.
2448 std::string relFromSource = this->Convert(fullPath, START);
2449 assert(!relFromSource.empty());
2450 bool relSource = !cmSystemTools::FileIsFullPath(relFromSource.c_str());
2451 bool subSource = relSource && relFromSource[0] != '.';
2453 // Try referencing the source relative to the binary tree.
2454 std::string relFromBinary = this->Convert(fullPath, START_OUTPUT);
2455 assert(!relFromBinary.empty());
2456 bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary.c_str());
2457 bool subBinary = relBinary && relFromBinary[0] != '.';
2459 // Select a nice-looking reference to the source file to construct
2460 // the object file name.
2461 std::string objectName;
2462 if((relSource && !relBinary) || (subSource && !subBinary))
2464 objectName = relFromSource;
2466 else if((relBinary && !relSource) || (subBinary && !subSource))
2468 objectName = relFromBinary;
2470 else if(relFromBinary.length() < relFromSource.length())
2472 objectName = relFromBinary;
2474 else
2476 objectName = relFromSource;
2479 // if it is still a full path check for the try compile case
2480 // try compile never have in source sources, and should not
2481 // have conflicting source file names in the same target
2482 if(cmSystemTools::FileIsFullPath(objectName.c_str()))
2484 if(this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile())
2486 objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
2490 // Replace the original source file extension with the object file
2491 // extension.
2492 bool keptSourceExtension = true;
2493 if(!source.GetPropertyAsBool("KEEP_EXTENSION"))
2495 // Decide whether this language wants to replace the source
2496 // extension with the object extension. For CMake 2.4
2497 // compatibility do this by default.
2498 bool replaceExt = this->NeedBackwardsCompatibility(2, 4);
2499 if(!replaceExt)
2501 std::string repVar = "CMAKE_";
2502 repVar += source.GetLanguage();
2503 repVar += "_OUTPUT_EXTENSION_REPLACE";
2504 replaceExt = this->Makefile->IsOn(repVar.c_str());
2507 // Remove the source extension if it is to be replaced.
2508 if(replaceExt)
2510 keptSourceExtension = false;
2511 std::string::size_type dot_pos = objectName.rfind(".");
2512 if(dot_pos != std::string::npos)
2514 objectName = objectName.substr(0, dot_pos);
2518 // Store the new extension.
2519 objectName +=
2520 this->GlobalGenerator->GetLanguageOutputExtension(source);
2522 if(hasSourceExtension)
2524 *hasSourceExtension = keptSourceExtension;
2527 // Convert to a safe name.
2528 return this->CreateSafeUniqueObjectFileName(objectName.c_str(), dir_len);
2531 //----------------------------------------------------------------------------
2532 const char*
2533 cmLocalGenerator
2534 ::GetSourceFileLanguage(const cmSourceFile& source)
2536 return source.GetLanguage();
2539 //----------------------------------------------------------------------------
2540 std::string cmLocalGenerator::EscapeForShellOldStyle(const char* str)
2542 std::string result;
2543 bool forceOn = cmSystemTools::GetForceUnixPaths();
2544 if(forceOn && this->WindowsShell)
2546 cmSystemTools::SetForceUnixPaths(false);
2548 result = cmSystemTools::EscapeSpaces(str);
2549 if(forceOn && this->WindowsShell)
2551 cmSystemTools::SetForceUnixPaths(true);
2553 return result;
2556 //----------------------------------------------------------------------------
2557 std::string cmLocalGenerator::EscapeForShell(const char* str, bool makeVars,
2558 bool forEcho)
2560 // Compute the flags for the target shell environment.
2561 int flags = 0;
2562 if(this->WindowsVSIDE)
2564 flags |= cmsysSystem_Shell_Flag_VSIDE;
2566 else
2568 flags |= cmsysSystem_Shell_Flag_Make;
2570 if(makeVars)
2572 flags |= cmsysSystem_Shell_Flag_AllowMakeVariables;
2574 if(forEcho)
2576 flags |= cmsysSystem_Shell_Flag_EchoWindows;
2578 if(this->WatcomWMake)
2580 flags |= cmsysSystem_Shell_Flag_WatcomWMake;
2582 if(this->MinGWMake)
2584 flags |= cmsysSystem_Shell_Flag_MinGWMake;
2586 if(this->NMake)
2588 flags |= cmsysSystem_Shell_Flag_NMake;
2591 // Compute the buffer size needed.
2592 int size = (this->WindowsShell ?
2593 cmsysSystem_Shell_GetArgumentSizeForWindows(str, flags) :
2594 cmsysSystem_Shell_GetArgumentSizeForUnix(str, flags));
2596 // Compute the shell argument itself.
2597 std::vector<char> arg(size);
2598 if(this->WindowsShell)
2600 cmsysSystem_Shell_GetArgumentForWindows(str, &arg[0], flags);
2602 else
2604 cmsysSystem_Shell_GetArgumentForUnix(str, &arg[0], flags);
2606 return std::string(&arg[0]);
2609 //----------------------------------------------------------------------------
2610 std::string cmLocalGenerator::EscapeForCMake(const char* str)
2612 // Always double-quote the argument to take care of most escapes.
2613 std::string result = "\"";
2614 for(const char* c = str; *c; ++c)
2616 if(*c == '"')
2618 // Escape the double quote to avoid ending the argument.
2619 result += "\\\"";
2621 else if(*c == '$')
2623 // Escape the dollar to avoid expanding variables.
2624 result += "\\$";
2626 else if(*c == '\\')
2628 // Escape the backslash to avoid other escapes.
2629 result += "\\\\";
2631 else
2633 // Other characters will be parsed correctly.
2634 result += *c;
2637 result += "\"";
2638 return result;
2641 //----------------------------------------------------------------------------
2642 std::string
2643 cmLocalGenerator::GetTargetDirectory(cmTarget const&) const
2645 cmSystemTools::Error("GetTargetDirectory"
2646 " called on cmLocalGenerator");
2647 return "";
2651 //----------------------------------------------------------------------------
2652 void
2653 cmLocalGenerator::GetTargetObjectFileDirectories(cmTarget* ,
2654 std::vector<std::string>&
2657 cmSystemTools::Error("GetTargetObjectFileDirectories"
2658 " called on cmLocalGenerator");
2661 //----------------------------------------------------------------------------
2662 unsigned int cmLocalGenerator::GetBackwardsCompatibility()
2664 // The computed version may change until the project is fully
2665 // configured.
2666 if(!this->BackwardsCompatibilityFinal)
2668 unsigned int major = 0;
2669 unsigned int minor = 0;
2670 unsigned int patch = 0;
2671 if(const char* value
2672 = this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY"))
2674 switch(sscanf(value, "%u.%u.%u", &major, &minor, &patch))
2676 case 2: patch = 0; break;
2677 case 1: minor = 0; patch = 0; break;
2678 default: break;
2681 this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
2682 this->BackwardsCompatibilityFinal = this->Configured;
2685 return this->BackwardsCompatibility;
2688 //----------------------------------------------------------------------------
2689 bool cmLocalGenerator::NeedBackwardsCompatibility(unsigned int major,
2690 unsigned int minor,
2691 unsigned int patch)
2693 // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
2694 // equal to or lower than the given version.
2695 unsigned int actual_compat = this->GetBackwardsCompatibility();
2696 return (actual_compat &&
2697 actual_compat <= CMake_VERSION_ENCODE(major, minor, patch));
2700 //----------------------------------------------------------------------------
2701 bool cmLocalGenerator::CheckDefinition(std::string const& define) const
2703 // Many compilers do not support -DNAME(arg)=sdf so we disable it.
2704 bool function_style = false;
2705 for(const char* c = define.c_str(); *c && *c != '='; ++c)
2707 if(*c == '(')
2709 function_style = true;
2710 break;
2713 if(function_style)
2715 cmOStringStream e;
2716 e << "WARNING: Function-style preprocessor definitions may not be "
2717 << "passed on the compiler command line because many compilers "
2718 << "do not support it.\n"
2719 << "CMake is dropping a preprocessor definition: " << define << "\n"
2720 << "Consider defining the macro in a (configured) header file.\n";
2721 cmSystemTools::Message(e.str().c_str());
2722 return false;
2725 // Many compilers do not support # in the value so we disable it.
2726 if(define.find_first_of("#") != define.npos)
2728 cmOStringStream e;
2729 e << "WARNING: Peprocessor definitions containing '#' may not be "
2730 << "passed on the compiler command line because many compilers "
2731 << "do not support it.\n"
2732 << "CMake is dropping a preprocessor definition: " << define << "\n"
2733 << "Consider defining the macro in a (configured) header file.\n";
2734 cmSystemTools::Message(e.str().c_str());
2735 return false;
2738 // Assume it is supported.
2739 return true;
2742 //----------------------------------------------------------------------------
2743 static std::string cmLGInfoProp(cmTarget* target, const char* prop)
2745 if(const char* val = target->GetProperty(prop))
2747 return val;
2749 else
2751 // For compatibility check for a variable.
2752 return target->GetMakefile()->GetSafeDefinition(prop);
2756 //----------------------------------------------------------------------------
2757 void cmLocalGenerator::GenerateAppleInfoPList(cmTarget* target,
2758 const char* targetName,
2759 const char* fname)
2761 std::string info_EXECUTABLE_NAME = targetName;
2763 // Lookup the properties.
2764 std::string info_INFO_STRING =
2765 cmLGInfoProp(target, "MACOSX_BUNDLE_INFO_STRING");
2766 std::string info_ICON_FILE =
2767 cmLGInfoProp(target, "MACOSX_BUNDLE_ICON_FILE");
2768 std::string info_GUI_IDENTIFIER =
2769 cmLGInfoProp(target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
2770 std::string info_LONG_VERSION_STRING =
2771 cmLGInfoProp(target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
2772 std::string info_BUNDLE_NAME =
2773 cmLGInfoProp(target, "MACOSX_BUNDLE_BUNDLE_NAME");
2774 std::string info_SHORT_VERSION_STRING =
2775 cmLGInfoProp(target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
2776 std::string info_BUNDLE_VERSION =
2777 cmLGInfoProp(target, "MACOSX_BUNDLE_BUNDLE_VERSION");
2778 std::string info_COPYRIGHT =
2779 cmLGInfoProp(target, "MACOSX_BUNDLE_COPYRIGHT");
2781 // Generate the file.
2782 cmGeneratedFileStream fout(fname);
2783 fout.SetCopyIfDifferent(true);
2784 fout <<
2785 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2786 "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\"\n"
2787 " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
2788 "<plist version=\"1.0\">\n"
2789 "<dict>\n"
2790 "\t<key>CFBundleDevelopmentRegion</key>\n"
2791 "\t<string>English</string>\n"
2792 "\t<key>CFBundleExecutable</key>\n"
2793 "\t<string>" << info_EXECUTABLE_NAME << "</string>\n"
2794 "\t<key>CFBundleGetInfoString</key>\n"
2795 "\t<string>" << info_INFO_STRING << "</string>\n"
2796 "\t<key>CFBundleIconFile</key>\n"
2797 "\t<string>" << info_ICON_FILE << "</string>\n"
2798 "\t<key>CFBundleIdentifier</key>\n"
2799 "\t<string>" << info_GUI_IDENTIFIER << "</string>\n"
2800 "\t<key>CFBundleInfoDictionaryVersion</key>\n"
2801 "\t<string>6.0</string>\n"
2802 "\t<key>CFBundleLongVersionString</key>\n"
2803 "\t<string>" << info_LONG_VERSION_STRING << "</string>\n"
2804 "\t<key>CFBundleName</key>\n"
2805 "\t<string>" << info_BUNDLE_NAME << "</string>\n"
2806 "\t<key>CFBundlePackageType</key>\n"
2807 "\t<string>APPL</string>\n"
2808 "\t<key>CFBundleShortVersionString</key>\n"
2809 "\t<string>" << info_SHORT_VERSION_STRING << "</string>\n"
2810 "\t<key>CFBundleSignature</key>\n"
2811 "\t<string>????" /* break string to avoid trigraph */ "</string>\n"
2812 "\t<key>CFBundleVersion</key>\n"
2813 "\t<string>" << info_BUNDLE_VERSION << "</string>\n"
2814 "\t<key>CSResourcesFileMapped</key>\n"
2815 "\t<true/>\n"
2816 "\t<key>LSRequiresCarbon</key>\n"
2817 "\t<true/>\n"
2818 "\t<key>NSHumanReadableCopyright</key>\n"
2819 "\t<string>" << info_COPYRIGHT << "</string>\n"
2820 "</dict>\n"
2821 "</plist>\n"