cmMakefile.cxx 41.5 KB
Newer Older
1
2
3
4
5
6
7
8
/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    $RCSfile$
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Will Schroeder's avatar
Will Schroeder committed
9
10
  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
11

Will Schroeder's avatar
Will Schroeder committed
12
13
14
     This software is distributed WITHOUT ANY WARRANTY; without even 
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
     PURPOSE.  See the above copyright notices for more information.
15
16

=========================================================================*/
17
#include "cmMakefile.h"
18
#include "cmCommand.h"
19
#include "cmStandardIncludes.h"
20
#include "cmSourceFile.h"
21
#include "cmDirectory.h"
22
#include "cmSystemTools.h"
Ken Martin's avatar
Ken Martin committed
23
24
#include "cmGlobalGenerator.h"
#include "cmLocalGenerator.h"
25
#include "cmCommands.h"
26
#include "cmCacheManager.h"
27
#include "cmFunctionBlocker.h"
28
#include "cmListFileCache.h"
29
#include "cmake.h"
30
#include <stdio.h>  // required for sprintf
31
32
33
34

// default is not to be building executables
cmMakefile::cmMakefile()
{
35
36
37
38
  // Setup the default include file regular expression (match everything).
  m_IncludeFileRegularExpression = "^.*$";
  // Setup the default include complaint regular expression (match nothing).
  m_ComplainFileRegularExpression = "^$";
39
40
41
42
43
44
  // Source and header file extensions that we can handle
  m_SourceFileExtensions.push_back( "cxx" );
  m_SourceFileExtensions.push_back( "cpp" );
  m_SourceFileExtensions.push_back( "c" );
  m_SourceFileExtensions.push_back( "M" );
  m_SourceFileExtensions.push_back( "m" );
Yves Starreveld's avatar
 
Yves Starreveld committed
45
  m_SourceFileExtensions.push_back( "mm" );
46
47

  m_HeaderFileExtensions.push_back( "h" );
48
  m_HeaderFileExtensions.push_back( "txx" );
49
  m_HeaderFileExtensions.push_back( "in" );
50
  
51
  m_DefineFlags = " ";
Ken Martin's avatar
Ken Martin committed
52
  m_LocalGenerator = 0;
53
54
55
  this->AddSourceGroup("", "^.*$");
  this->AddSourceGroup("Source Files", "\\.(cpp|C|c|cxx|rc|def|r|odl|idl|hpj|bat)$");
  this->AddSourceGroup("Header Files", "\\.(h|hh|hpp|hxx|hm|inl)$");
56
  this->AddDefaultCommands();
57
  this->AddDefaultDefinitions();
58
59
}

60
61
unsigned int cmMakefile::GetCacheMajorVersion()
{
Ken Martin's avatar
Ken Martin committed
62
  if(!this->GetCacheManager()->GetCacheValue("CMAKE_CACHE_MAJOR_VERSION"))
63
64
65
    {
    return 0;
    }
Ken Martin's avatar
Ken Martin committed
66
  return atoi(this->GetCacheManager()->GetCacheValue("CMAKE_CACHE_MAJOR_VERSION"));
67
68
69
70
}

unsigned int cmMakefile::GetCacheMinorVersion()
{
Ken Martin's avatar
Ken Martin committed
71
  if(!this->GetCacheManager()->GetCacheValue("Cmake_Cache_MINOR_VERSION"))
72
73
74
    {
    return 0;
    }
Ken Martin's avatar
Ken Martin committed
75
  return atoi(this->GetCacheManager()->GetCacheValue("CMAKE_CACHE_MINOR_VERSION"));
76
77
78
}


79
void cmMakefile::AddDefaultCommands()
80
{
81
82
83
84
85
86
87
  std::list<cmCommand*> commands;
  GetPredefinedCommands(commands);
  for(std::list<cmCommand*>::iterator i = commands.begin();
      i != commands.end(); ++i)
    {
    this->AddCommand(*i);
    }
Bill Hoffman's avatar
Bill Hoffman committed
88
#if defined(_WIN32) || defined(__CYGWIN__)
89
90
91
92
  this->AddDefinition("WIN32", "1");
#else
  this->AddDefinition("UNIX", "1");
#endif
93
  // Cygwin is more like unix so enable the unix commands
94
95
#if defined(__CYGWIN__)
  this->AddDefinition("UNIX", "1");
Bill Hoffman's avatar
Bill Hoffman committed
96
97
98
99
  this->AddDefinition("CYGWIN", "1");
#endif
#if defined(__APPLE__)
  this->AddDefinition("APPLE", "1");
100
101
102
103
104
#endif
}

cmMakefile::~cmMakefile()
{
105
106
107
108
109
  for(std::vector<cmSourceFile*>::iterator i = m_SourceFiles.begin();
      i != m_SourceFiles.end(); ++i)
    {
    delete *i;
    }
110
  for(unsigned int i=0; i < m_UsedCommands.size(); i++)
111
    {
112
    delete m_UsedCommands[i];
113
    }
114
115
  for(RegisteredCommandsMap::iterator j = m_Commands.begin();
      j != m_Commands.end(); ++j)
116
117
118
    {
    delete (*j).second;
    }
119
120
121
122
123
124
125
126
  for(DataMap::const_iterator d = m_DataMap.begin();
      d != m_DataMap.end(); ++d)
    {
    if(d->second)
      {
      delete d->second;
      }
    }
Bill Hoffman's avatar
Bill Hoffman committed
127
  std::list<cmFunctionBlocker *>::iterator pos;
Bill Hoffman's avatar
Bill Hoffman committed
128
  for (pos = m_FunctionBlockers.begin(); 
129
       pos != m_FunctionBlockers.end(); pos = m_FunctionBlockers.begin())
Bill Hoffman's avatar
Bill Hoffman committed
130
131
    {
    cmFunctionBlocker* b = *pos;
132
    m_FunctionBlockers.remove(*pos);
Bill Hoffman's avatar
Bill Hoffman committed
133
134
    delete b;
    }
135
136
}

137
void cmMakefile::PrintStringVector(const char* s, const std::vector<std::string>& v) const
138
139
{
  std::cout << s << ": ( \n";
140
  for(std::vector<std::string>::const_iterator i = v.begin();
141
142
143
144
145
      i != v.end(); ++i)
    {
    std::cout << (*i).c_str() << " ";
    }
  std::cout << " )\n";
146
147
148
149
}


// call print on all the classes in the makefile
150
void cmMakefile::Print() const
151
{
152
  // print the class lists
153
  std::cout << "classes:\n";
154

155
156
157
158
159
160
161
  std::cout << " m_Targets: ";
  for (cmTargets::const_iterator l = m_Targets.begin();
       l != m_Targets.end(); l++)
    {
    std::cout << l->first << std::endl;
    }

Ken Martin's avatar
Ken Martin committed
162
163
164
165
166
167
  std::cout << " m_CurrentOutputDirectory; " << 
    m_CurrentOutputDirectory.c_str() << std::endl;
  std::cout << " m_StartOutputDirectory; " << 
    m_StartOutputDirectory.c_str() << std::endl;
  std::cout << " m_HomeOutputDirectory; " << 
    m_HomeOutputDirectory.c_str() << std::endl;
168
169
  std::cout << " m_cmCurrentDirectory; " << 
    m_cmCurrentDirectory.c_str() << std::endl;
Ken Martin's avatar
Ken Martin committed
170
171
172
173
  std::cout << " m_cmStartDirectory; " << 
    m_cmStartDirectory.c_str() << std::endl;
  std::cout << " m_cmHomeDirectory; " << 
    m_cmHomeDirectory.c_str() << std::endl;
174
175
176
177
  std::cout << " m_ProjectName;	" <<  m_ProjectName.c_str() << std::endl;
  this->PrintStringVector("m_SubDirectories ", m_SubDirectories); 
  this->PrintStringVector("m_IncludeDirectories;", m_IncludeDirectories);
  this->PrintStringVector("m_LinkDirectories", m_LinkDirectories);
178
179
180
181
182
  for( std::vector<cmSourceGroup>::const_iterator i = m_SourceGroups.begin();
       i != m_SourceGroups.end(); ++i)
    {
    i->Print();
    }
183
184
}

185
186
187
188
bool cmMakefile::CommandExists(const char* name) const
{
  return (m_Commands.find(name) != m_Commands.end());
}
Ken Martin's avatar
Ken Martin committed
189
      
Ken Martin's avatar
Ken Martin committed
190
void cmMakefile::ExecuteCommand(std::string const &name,
191
                                std::vector<std::string> const& arguments)
Ken Martin's avatar
Ken Martin committed
192
{
193
194
195
196
197
198
  // quick return if blocked
  if(this->IsFunctionBlocked(name.c_str(), arguments))
    {
    return;
    }
  // execute the command
Ken Martin's avatar
Ken Martin committed
199
200
201
202
203
204
205
206
207
208
209
210
211
  RegisteredCommandsMap::iterator pos = m_Commands.find(name);
  if(pos != m_Commands.end())
    {
    cmCommand* rm = (*pos).second;
    cmCommand* usedCommand = rm->Clone();
    usedCommand->SetMakefile(this);
    bool keepCommand = false;
    if(usedCommand->GetEnabled())
      {
      // if not running in inherit mode or
      // if the command is inherited then InitialPass it.
      if(!m_Inheriting || usedCommand->IsInherited())
        {
212
213
214
        std::vector<std::string> expandedArguments;
        for(std::vector<std::string>::const_iterator i = arguments.begin();
            i != arguments.end(); ++i)
215
          {
216
217
218
219
220
221
222
          std::string tmps = *i;
          this->ExpandVariablesInString(tmps);
          if (tmps.find_first_not_of(" ") != std::string::npos)
            {
            // we found something in the args
            expandedArguments.push_back(tmps);
            }
223
224
          }
        if(!usedCommand->InitialPass(expandedArguments))
Ken Martin's avatar
Ken Martin committed
225
          {
226
227
228
229
230
231
232
	  std::string error;
	  error = usedCommand->GetName();
	  error += ": Error : \n";
	  error += usedCommand->GetError();
	  error += " from CMakeLists.txt file in directory: ";
	  error += m_cmCurrentDirectory;
          cmSystemTools::Error(error.c_str());
Ken Martin's avatar
Ken Martin committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
          }
        else
          {
          // use the command
          keepCommand = true;
          m_UsedCommands.push_back(usedCommand);
          }
        }
      }
    // if the Cloned command was not used 
    // then delete it
    if(!keepCommand)
      {
      delete usedCommand;
      }
    }
249
250
251
252
253
254
255
  else if((name == "CABLE_WRAP_TCL") || (name == "CABLE_CLASS_SET") ||
          (name == "CONFIGURE_GCCXML"))
    {
    cmSystemTools::Error("The command ", name.c_str(),
                         " is not implemented in this version of CMake.\n"
                         "Contact cable@public.kitware.com for more information.");
    }
Ken Martin's avatar
Ken Martin committed
256
257
  else
    {
258
259
260
    cmSystemTools::Error("unknown CMake command:", name.c_str(), 
                         "\nReading cmake file in directory:" , 
                         m_cmCurrentDirectory.c_str());
Ken Martin's avatar
Ken Martin committed
261
262
263
    }
}

264
// Parse the given CMakeLists.txt file into a list of classes.
Ken Martin's avatar
Ken Martin committed
265
266
// Reads in current CMakeLists file and all parent CMakeLists files
// executing all inherited commands in the parents
Anonymous's avatar
Anonymous committed
267
268
269
270
271
272
273
//
//   if external is non-zero, this means that we have branched to grab some
//   commands from a remote list-file (that is, the equivalent of a
//   #include has been called).  We DO NOT look at the parents of this
//   list-file, and for all other purposes, the name of this list-file
//   is "filename" and not "external".
bool cmMakefile::ReadListFile(const char* filename, const char* external)
274
{
275
276
277
278
279
  // used to watch for blockers going out of scope
  // e.g. mismatched IF statement
  std::set<cmFunctionBlocker *> originalBlockers;

      // keep track of the current file being read
280
281
  if (filename)
    {
Bill Hoffman's avatar
Bill Hoffman committed
282
283
284
285
    if(m_cmCurrentListFile != filename)
      {
      m_cmCurrentListFile = filename;
      }
286
    // loop over current function blockers and record them
Bill Hoffman's avatar
Bill Hoffman committed
287
    std::list<cmFunctionBlocker *>::iterator pos;
288
289
290
291
292
    for (pos = m_FunctionBlockers.begin(); 
         pos != m_FunctionBlockers.end(); ++pos)
      {
      originalBlockers.insert(*pos);
      }
293
    }
294
  
Anonymous's avatar
Anonymous committed
295
296
297
298
  // if this is not a remote makefile
  //  (if it were, this would be called from the "filename" call,
  //   rather than the "external" call)
  if (!external)
299
    {
Anonymous's avatar
Anonymous committed
300
301
302
303
304
305
      // is there a parent CMakeLists file that does not go beyond the
      // Home directory? if so recurse and read in that List file 
      std::string parentList = this->GetParentListFileName(filename);
      if (parentList != "")
	{
	  std::string srcdir = m_cmCurrentDirectory;
306
307
308
309
310
311
312
313
314
          std::string bindir = m_CurrentOutputDirectory;

	  std::string::size_type pos = parentList.rfind('/');

          m_cmCurrentDirectory = parentList.substr(0, pos);
	  m_CurrentOutputDirectory = m_HomeOutputDirectory + parentList.substr(m_cmHomeDirectory.size(), pos - m_cmHomeDirectory.size());

	  // if not found, oops
	  if(pos == std::string::npos)
Anonymous's avatar
Anonymous committed
315
	    {
316
            cmSystemTools::Error("Trailing slash not found");
Anonymous's avatar
Anonymous committed
317
	    }
318

Anonymous's avatar
Anonymous committed
319
	  this->ReadListFile(parentList.c_str());
320

Anonymous's avatar
Anonymous committed
321
322
323
324
	  // restore the current directory
	  m_cmCurrentDirectory = srcdir;
	  m_CurrentOutputDirectory = bindir;    
	}
325
    }
Ken Martin's avatar
Ken Martin committed
326
327
328

  // are we at the start CMakeLists file or are we processing a parent 
  // lists file
Anonymous's avatar
Anonymous committed
329
330
331
  //
  //   this might, or might not be true, irrespective if we are
  //   off looking at an external makefile.
Ken Martin's avatar
Ken Martin committed
332
  m_Inheriting = (m_cmCurrentDirectory != m_cmStartDirectory);
Ken Martin's avatar
Ken Martin committed
333
                    
334
  // Now read the input file
Anonymous's avatar
Anonymous committed
335
336
337
  const char *filenametoread= filename;

  if( external)
338
    {
Anonymous's avatar
Anonymous committed
339
    filenametoread= external;
340
    }
341
342
343
344

  cmListFile* lf = 
    cmListFileCache::GetInstance()->GetFileCache(filenametoread);
  if(!lf)
345
346
347
    {
    return false;
    }
348
349
  // add this list file to the list of dependencies
  m_ListFiles.push_back( filenametoread);
350
351
  const size_t numberFunctions = lf->m_Functions.size();
  for(size_t i =0; i < numberFunctions; ++i)
352
    {
353
    cmListFileFunction& curFunction = lf->m_Functions[i];
354
355
    this->ExecuteCommand(curFunction.m_Name,
                         curFunction.m_Arguments);
356
    }
Ken Martin's avatar
Ken Martin committed
357
358
359
360
361

  // send scope ended to and funciton blockers
  if (filename)
    {
    // loop over all function blockers to see if any block this command
Bill Hoffman's avatar
Bill Hoffman committed
362
    std::list<cmFunctionBlocker *>::iterator pos;
Ken Martin's avatar
Ken Martin committed
363
364
365
    for (pos = m_FunctionBlockers.begin(); 
         pos != m_FunctionBlockers.end(); ++pos)
      {
366
367
368
369
370
371
      // if this blocker was not in the original then send a 
      // scope ended message
      if (originalBlockers.find(*pos) == originalBlockers.end())
        {
        (*pos)->ScopeEnded(*this);
        }
Ken Martin's avatar
Ken Martin committed
372
373
374
      }
    }
  
375
376
  return true;
}
377

378

379
void cmMakefile::AddCommand(cmCommand* wg)
380
381
{
  std::string name = wg->GetName();
382
  m_Commands.insert( RegisteredCommandsMap::value_type(name, wg));
383
384
385
}

  // Set the make file 
Ken Martin's avatar
Ken Martin committed
386
void cmMakefile::SetLocalGenerator(cmLocalGenerator* lg)
387
{
Ken Martin's avatar
Ken Martin committed
388
  m_LocalGenerator = lg;
389
390
}

391
void cmMakefile::FinalPass()
392
393
{
  // do all the variable expansions here
394
  this->ExpandVariables();
395

396
  // give all the commands a chance to do something
397
  // after the file has been parsed before generation
398
399
  for(std::vector<cmCommand*>::iterator i = m_UsedCommands.begin();
      i != m_UsedCommands.end(); ++i)
400
401
    {
    (*i)->FinalPass();
402
    }
403
404
405
406
407
408
409

}

  // Generate the output file
void cmMakefile::GenerateMakefile()
{
  this->FinalPass();
410
411
412
  const char* versionValue
    = this->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION");
  bool oldVersion = (!versionValue || atof(versionValue) < 1.4);
413
  // merge libraries
414
  
415
416
417
  for (cmTargets::iterator l = m_Targets.begin();
       l != m_Targets.end(); l++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
418
    l->second.GenerateSourceFilesFromSourceLists(*this);
419
420
421
422
423
    // pick up any LINK_LIBRARIES that were added after the target
    if(oldVersion)
      {
      this->AddGlobalLinkInformation(l->first.c_str(), l->second);
      }
424
    l->second.AnalyzeLibDependencies(*this);
425
    }
426
427
}

428

429
430
void cmMakefile::AddCustomCommand(const char* source,
                                  const char* command,
Ken Martin's avatar
Ken Martin committed
431
                                  const std::vector<std::string>& commandArgs,
432
                                  const std::vector<std::string>& depends,
433
434
                                  const std::vector<std::string>& outputs,
                                  const char *target) 
435
{
436
437
438
  // find the target, 
  if (m_Targets.find(target) != m_Targets.end())
    {
439
440
441
    std::string expandC = command;
    this->ExpandVariablesInString(expandC);
    std::string c = cmSystemTools::EscapeSpaces(expandC.c_str());
Ken Martin's avatar
Ken Martin committed
442
443

    std::string combinedArgs;
Bill Hoffman's avatar
Bill Hoffman committed
444
    unsigned int i;
Ken Martin's avatar
Ken Martin committed
445
446
447
448
449
450
451
452
    
    for (i = 0; i < commandArgs.size(); ++i)
      {
      combinedArgs += cmSystemTools::EscapeSpaces(commandArgs[i].c_str());
      combinedArgs += " ";
      }
    
    cmCustomCommand cc(source,c.c_str(),combinedArgs.c_str(),depends,outputs);
453
    m_Targets[target].GetCustomCommands().push_back(cc);
454
455
    std::string cacheCommand = command;
    this->ExpandVariablesInString(cacheCommand);
Ken Martin's avatar
Ken Martin committed
456
    if(this->GetCacheManager()->GetCacheValue(cacheCommand.c_str()))
457
458
      {
      m_Targets[target].AddUtility(
Ken Martin's avatar
Ken Martin committed
459
        this->GetCacheManager()->GetCacheValue(cacheCommand.c_str()));
460
      }
461
    }
462
}
463

464
void cmMakefile::AddCustomCommand(const char* source,
465
                                  const char* command,
Ken Martin's avatar
Ken Martin committed
466
                                  const std::vector<std::string>& commandArgs,
467
                                  const std::vector<std::string>& depends,
468
469
                                  const char* output, 
                                  const char *target) 
470
{
471
472
  std::vector<std::string> outputs;
  outputs.push_back(output);
473
  this->AddCustomCommand(source, command, commandArgs, depends, outputs, target);
474
475
476
477
478
479
480
481
}

void cmMakefile::AddDefineFlag(const char* flag)
{
  m_DefineFlags += " ";
  m_DefineFlags += flag;
}

482

483
void cmMakefile::AddLinkLibrary(const char* lib, cmTarget::LinkLibraryType llt)
484
485
{
  m_LinkLibraries.push_back(
486
487
488
489
490
491
	  std::pair<std::string, cmTarget::LinkLibraryType>(lib,llt));
}

void cmMakefile::AddLinkLibraryForTarget(const char *target,
                                         const char* lib, 
                                         cmTarget::LinkLibraryType llt)
492
493
494
{ 
  cmTargets::iterator i = m_Targets.find(target);
  if ( i != m_Targets.end())
495
    {
496
    i->second.AddLinkLibrary( *this, target, lib, llt );
497
    }
Berk Geveci's avatar
Berk Geveci committed
498
499
500
501
  else
    {
    cmSystemTools::Error("Attempt to add link libraries to non-existant target: ",  target, " for lib ", lib);
    }
502
503
}

504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
void cmMakefile::AddLinkDirectoryForTarget(const char *target,
                                           const char* d)
{
  cmTargets::iterator i = m_Targets.find(target);
  if ( i != m_Targets.end())
    {
    i->second.AddLinkDirectory( d );
    }
  else
    {
    cmSystemTools::Error("Attempt to add link directories to non-existant target: ", 
                         target, " for directory ", d);
    }
}

519
520
void cmMakefile::AddLinkLibrary(const char* lib)
{
521
  this->AddLinkLibrary(lib,cmTarget::GENERAL);
522
523
524
525
}

void cmMakefile::AddLinkDirectory(const char* dir)
{
526
527
528
529
  // Don't add a link directory that is already present.  Yes, this
  // linear search results in n^2 behavior, but n won't be getting
  // much bigger than 20.  We cannot use a set because of order
  // dependency of the link search path.
530
531
532
533
534
535
536
537
538
539
540
541
542
  
  // remove trailing slashes
  if(dir && dir[strlen(dir)-1] == '/')
    {
    std::string newdir = dir;
    newdir = newdir.substr(0, newdir.size()-1);
    if(std::find(m_LinkDirectories.begin(),
                 m_LinkDirectories.end(), newdir.c_str()) == m_LinkDirectories.end())
      {
      m_LinkDirectories.push_back(newdir);
      }
    }
  else
543
    {
544
545
546
547
548
    if(std::find(m_LinkDirectories.begin(),
                 m_LinkDirectories.end(), dir) == m_LinkDirectories.end())
      {
      m_LinkDirectories.push_back(dir);
      }
549
    }
550
551
552
553
554
555
556
}

void cmMakefile::AddSubDirectory(const char* sub)
{
  m_SubDirectories.push_back(sub);
}

557
void cmMakefile::AddIncludeDirectory(const char* inc, bool before)
558
{
559
560
561
562
563
564
565
  // Don't add an include directory that is already present.  Yes,
  // this linear search results in n^2 behavior, but n won't be
  // getting much bigger than 20.  We cannot use a set because of
  // order dependency of the include path.
  if(std::find(m_IncludeDirectories.begin(),
               m_IncludeDirectories.end(), inc) == m_IncludeDirectories.end())
    {
566
567
568
569
570
571
572
573
574
    if (before)
      {
      // WARNING: this *is* expensive (linear time) since it's a vector
      m_IncludeDirectories.insert(m_IncludeDirectories.begin(), inc);
      }
    else
      {
      m_IncludeDirectories.push_back(inc);
      }
575
    }
576
577
}

578

579
580
void cmMakefile::AddDefinition(const char* name, const char* value)
{
581
  m_Definitions.erase( DefinitionMap::key_type(name));
582
583
  m_Definitions.insert(DefinitionMap::value_type(name, value));
}
584

585
586
587
588
589

void cmMakefile::AddCacheDefinition(const char* name, const char* value, 
                                    const char* doc,
                                    cmCacheManager::CacheEntryType type)
{
Ken Martin's avatar
Ken Martin committed
590
  this->GetCacheManager()->AddCacheEntry(name, value, doc, type);
591
592
593
594
  this->AddDefinition(name, value);
}


595
596
597
598
void cmMakefile::AddDefinition(const char* name, bool value)
{
  if(value)
    {
599
    m_Definitions.erase( DefinitionMap::key_type(name));
600
601
602
603
    m_Definitions.insert(DefinitionMap::value_type(name, "ON"));
    }
  else
    {
604
    m_Definitions.erase( DefinitionMap::key_type(name));
605
606
607
    m_Definitions.insert(DefinitionMap::value_type(name, "OFF"));
    }
}
608

609
610
611

void cmMakefile::AddCacheDefinition(const char* name, bool value, const char* doc)
{
Ken Martin's avatar
Ken Martin committed
612
  this->GetCacheManager()->AddCacheEntry(name, value, doc);
613
614
615
  this->AddDefinition(name, value);
}

616
617
618
619
620
void cmMakefile::SetProjectName(const char* p)
{
  m_ProjectName = p;
}

621
622
623

void cmMakefile::AddGlobalLinkInformation(const char* name, cmTarget& target)
{
624
625
626
  // for these targets do not add anything
  switch(target.GetType())
    {
Brad King's avatar
Brad King committed
627
628
629
630
    case cmTarget::UTILITY: return;
    case cmTarget::INSTALL_FILES: return;
    case cmTarget::INSTALL_PROGRAMS: return;
    default:;
631
    }
632
633
634
635
636
637
  std::vector<std::string>::iterator j;
  for(j = m_LinkDirectories.begin();
      j != m_LinkDirectories.end(); ++j)
    {
    target.AddLinkDirectory(j->c_str());
    }
638
  target.MergeLinkLibraries( *this, name, m_LinkLibraries );
639
640
641
}


Yves Starreveld's avatar
 
Yves Starreveld committed
642
void cmMakefile::AddLibrary(const char* lname, int shared,
643
                            const std::vector<std::string> &srcs)
644
645
{
  cmTarget target;
Yves Starreveld's avatar
 
Yves Starreveld committed
646
647
648
649
650
651
652
653
654
655
656
657
658
659
  switch (shared)
    {
    case 0:
      target.SetType(cmTarget::STATIC_LIBRARY);
      break;
    case 1:
      target.SetType(cmTarget::SHARED_LIBRARY);
      break;
    case 2:
      target.SetType(cmTarget::MODULE_LIBRARY);
      break;
    default:
      target.SetType(cmTarget::STATIC_LIBRARY);
    }
Bill Hoffman's avatar
Bill Hoffman committed
660
661
662
663
664
  // Clear its dependencies. Otherwise, dependencies might persist
  // over changes in CMakeLists.txt, making the information stale and
  // hence useless.
  std::string depname = lname;
  depname += "_LIB_DEPENDS";
Ken Martin's avatar
Ken Martin committed
665
  this->GetCacheManager()->
Bill Hoffman's avatar
Bill Hoffman committed
666
    AddCacheEntry(depname.c_str(), "",
667
                  "Dependencies for target", cmCacheManager::STATIC);
Yves Starreveld's avatar
 
Yves Starreveld committed
668

Bill Hoffman's avatar
Bill Hoffman committed
669
  
Ken Martin's avatar
Ken Martin committed
670
  target.SetInAll(true);
671
  target.GetSourceLists() = srcs;
672
  this->AddGlobalLinkInformation(lname, target);
673
  m_Targets.insert(cmTargets::value_type(lname,target));
674
675

  // Add an entry into the cache 
676
677
  std::string libPath = lname;
  libPath += "_CMAKE_PATH";
Ken Martin's avatar
Ken Martin committed
678
  this->GetCacheManager()->
679
    AddCacheEntry(libPath.c_str(),
680
681
                  this->GetCurrentOutputDirectory(),
                  "Path to a library", cmCacheManager::INTERNAL);
682
683
684
685

  // Add an entry into the cache
  std::string ltname = lname;
  ltname += "_LIBRARY_TYPE";
Yves Starreveld's avatar
 
Yves Starreveld committed
686
687
688
  switch (shared)
    {
    case 0:
Ken Martin's avatar
Ken Martin committed
689
      this->GetCacheManager()->AddCacheEntry(ltname.c_str(),"STATIC",
Yves Starreveld's avatar
 
Yves Starreveld committed
690
691
692
693
		      "Whether a library is static, shared or module.",
		      cmCacheManager::INTERNAL);
      break;
    case 1:
Ken Martin's avatar
Ken Martin committed
694
      this->GetCacheManager()->
Yves Starreveld's avatar
 
Yves Starreveld committed
695
696
697
698
699
700
	AddCacheEntry(ltname.c_str(),
		      "SHARED",
		      "Whether a library is static, shared or module.",
		      cmCacheManager::INTERNAL);
      break;
    case 2:
Ken Martin's avatar
Ken Martin committed
701
      this->GetCacheManager()->
Yves Starreveld's avatar
 
Yves Starreveld committed
702
703
704
705
706
707
	AddCacheEntry(ltname.c_str(),
		      "MODULE",
		      "Whether a library is static, shared or module.",
		      cmCacheManager::INTERNAL);
      break;
    default:
Ken Martin's avatar
Ken Martin committed
708
      this->GetCacheManager()->
Yves Starreveld's avatar
 
Yves Starreveld committed
709
710
711
712
713
	AddCacheEntry(ltname.c_str(),
		      "STATIC",
		      "Whether a library is static, shared or module.",
		      cmCacheManager::INTERNAL);
    }
714

715
716
717
718
}

void cmMakefile::AddExecutable(const char *exeName, 
                               const std::vector<std::string> &srcs)
719
720
721
722
723
724
725
{
  this->AddExecutable(exeName,srcs,false);
}

void cmMakefile::AddExecutable(const char *exeName, 
                               const std::vector<std::string> &srcs,
                               bool win32)
726
{
727
  cmTarget target;
728
729
730
731
732
733
734
735
  if (win32)
    {
    target.SetType(cmTarget::WIN32_EXECUTABLE);
    }
  else
    {
    target.SetType(cmTarget::EXECUTABLE);
    }
Ken Martin's avatar
Ken Martin committed
736
  target.SetInAll(true);
737
  target.GetSourceLists() = srcs;
738
  this->AddGlobalLinkInformation(exeName, target);
739
740
  m_Targets.insert(cmTargets::value_type(exeName,target));
  
741
742
  
  // Add an entry into the cache 
743
744
  std::string exePath = exeName;
  exePath += "_CMAKE_PATH";
Ken Martin's avatar
Ken Martin committed
745
  this->GetCacheManager()->
746
    AddCacheEntry(exePath.c_str(),
747
748
                  this->GetCurrentOutputDirectory(),
                  "Path to an executable", cmCacheManager::INTERNAL);
749
750
}

751

752
void cmMakefile::AddUtilityCommand(const char* utilityName,
753
                                   const char* command,
754
                                   const char* arguments,
755
756
757
                                   bool all)
{
  std::vector<std::string> empty;
758
  this->AddUtilityCommand(utilityName,command,arguments,all,
759
760
761
762
763
                          empty,empty);
}

void cmMakefile::AddUtilityCommand(const char* utilityName,
                                   const char* command,
764
                                   const char* arguments,
765
766
767
                                   bool all,
                                   const std::vector<std::string> &dep,
                                   const std::vector<std::string> &out)
768
769
770
{
  cmTarget target;
  target.SetType(cmTarget::UTILITY);
771
  target.SetInAll(all);
772
  cmCustomCommand cc(utilityName, command, arguments, dep, out);
773
774
775
776
777
  target.GetCustomCommands().push_back(cc);
  m_Targets.insert(cmTargets::value_type(utilityName,target));
}


778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
void cmMakefile::AddSourceGroup(const char* name, const char* regex)
{
  // First see if the group exists.  If so, replace its regular expression.
  for(std::vector<cmSourceGroup>::iterator sg = m_SourceGroups.begin();
      sg != m_SourceGroups.end(); ++sg)
    {
    std::string sgName = sg->GetName();
    if(sgName == name)
      {
      // We only want to set the regular expression.  If there are already
      // source files in the group, we don't want to remove them.
      sg->SetGroupRegex(regex);
      return;
      }
    }
  
  // The group doesn't exist.  Add it.
  m_SourceGroups.push_back(cmSourceGroup(name, regex));
}
797
798
799
800
801

void cmMakefile::AddExtraDirectory(const char* dir)
{
  m_AuxSourceDirectories.push_back(dir);
}
802

803

Ken Martin's avatar
Ken Martin committed
804
805
806
807
808
// return the file name for the parent CMakeLists file to the 
// one passed in. Zero is returned if the CMakeLists file is the
// one in the home directory or if for some reason a parent cmake lists 
// file cannot be found.
std::string cmMakefile::GetParentListFileName(const char *currentFileName)
809
{
Ken Martin's avatar
Ken Martin committed
810
811
812
813
814
815
  // extract the directory name
  std::string parentFile;
  std::string listsDir = currentFileName;
  std::string::size_type pos = listsDir.rfind('/');
  // if we could not find the directory return 0
  if(pos == std::string::npos)
816
    {
Ken Martin's avatar
Ken Martin committed
817
    return parentFile;
818
    }
Ken Martin's avatar
Ken Martin committed
819
820
821
822
  listsDir = listsDir.substr(0, pos);
  
  // if we are in the home directory then stop, return 0
  if(m_cmHomeDirectory == listsDir)
823
    {
Ken Martin's avatar
Ken Martin committed
824
    return parentFile;
825
    }
Ken Martin's avatar
Ken Martin committed
826
827
828
829
830
831
832
833
834
835
836
837
838
  
  // is there a parent directory we can check
  pos = listsDir.rfind('/');
  // if we could not find the directory return 0
  if(pos == std::string::npos)
    {
    return parentFile;
    }
  listsDir = listsDir.substr(0, pos);
  
  // is there a CMakeLists.txt file in the parent directory ?
  parentFile = listsDir;
  parentFile += "/CMakeLists.txt";
839
  while(!cmSystemTools::FileExists(parentFile.c_str()))
840
    {
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
    // There is no CMakeLists.txt file in the parent directory.  This
    // can occur when coming out of a subdirectory resulting from a
    // SUBDIRS(Foo/Bar) command (coming out of Bar into Foo).  Try
    // walking up until a CMakeLists.txt is found or the home
    // directory is hit.
    
    // if we are in the home directory then stop, return 0
    if(m_cmHomeDirectory == listsDir) { return ""; }
    
    // is there a parent directory we can check
    pos = listsDir.rfind('/');
    // if we could not find the directory return 0
    if(pos == std::string::npos) { return ""; }
    listsDir = listsDir.substr(0, pos);
    parentFile = listsDir;
    parentFile += "/CMakeLists.txt";
857
    }
858

Ken Martin's avatar
Ken Martin committed
859
  return parentFile;
860
861
}

862
863
864
// expance CMAKE_BINARY_DIR and CMAKE_SOURCE_DIR in the
// include and library directories.

865
void cmMakefile::ExpandVariables()
866
{
867
  // Now expand varibles in the include and link strings
868
869
  for(std::vector<std::string>::iterator d = m_IncludeDirectories.begin();
        d != m_IncludeDirectories.end(); ++d)
870
    {
871
    this->ExpandVariablesInString(*d);
872
    }
873
874
  for(std::vector<std::string>::iterator d = m_LinkDirectories.begin();
        d != m_LinkDirectories.end(); ++d)
875
    {
876
    this->ExpandVariablesInString(*d);
877
    }
878
879
  for(cmTarget::LinkLibraries::iterator l = m_LinkLibraries.begin();
      l != m_LinkLibraries.end(); ++l)
880
    {
881
    this->ExpandVariablesInString(l->first);
882
883
884
    }
}

885
bool cmMakefile::IsOn(const char* name) const
886
887
888
889
890
{
  const char* value = this->GetDefinition(name);
  return cmSystemTools::IsOn(value);
}

891
const char* cmMakefile::GetDefinition(const char* name) const
892
{
893
  DefinitionMap::const_iterator pos = m_Definitions.find(name);
894
895
896
897
  if(pos != m_Definitions.end())
    {
    return (*pos).second.c_str();
    }
Ken Martin's avatar
Ken Martin committed
898
  return this->GetCacheManager()->GetCacheValue(name);
899
}
900

901
int cmMakefile::DumpDocumentationToFile(std::ostream& f)
902
903
904
{
  // Open the supplied filename
  
905
  // Loop over all registered commands and print out documentation
906
907
908
  const char *name;
  const char *terse;
  const char *full;
Bill Hoffman's avatar
Bill Hoffman committed
909
910
911
912
913
914
  char tmp[1024];
  sprintf(tmp,"Version %d.%d", cmMakefile::GetMajorVersion(),
          cmMakefile::GetMinorVersion());
  f << "<html>\n";
  f << "<h1>Documentation for commands of CMake " << tmp << "</h1>\n";
  f << "<ul>\n";
915
916
  for(RegisteredCommandsMap::iterator j = m_Commands.begin();
      j != m_Commands.end(); ++j)
917
918
    {
    name = (*j).second->GetName();
919
920
    terse = (*j).second->GetTerseDocumentation();
    full = (*j).second->GetFullDocumentation();
Bill Hoffman's avatar
Bill Hoffman committed
921
922
    f << "<li><b>" << name << "</b> - " << terse << std::endl
      << "<br><i>Usage:</i> " << full << "</li>" << std::endl << std::endl;
923
    }
Bill Hoffman's avatar
Bill Hoffman committed
924
  f << "</ul></html>\n";
925
926
927
  return 1;
}

928

929
const char *cmMakefile::ExpandVariablesInString(std::string& source) const
930
{
931
  return this->ExpandVariablesInString(source, false);
932
933
}

934
const char *cmMakefile::ExpandVariablesInString(std::string& source,
935
936
                                                bool escapeQuotes,
                                                bool atOnly) const
937
{
938
  // This method replaces ${VAR} and @VAR@ where VAR is looked up
939
  // with GetDefinition(), if not found in the map, nothing is expanded.
940
941
  // It also supports the $ENV{VAR} syntax where VAR is looked up in
  // the current environment variables.
942

943
  // start by look for $ or @ in the string
944
945
946
947
948
949
950
951
952
  std::string::size_type markerPos;
  if(atOnly)
    {
    markerPos = source.find_first_of("@");
    }
  else
    {
    markerPos = source.find_first_of("$@");
    }
953
954
955
  // if not found, or found as the last character, then leave quickly as
  // nothing needs to be expanded
  if((markerPos == std::string::npos) || (markerPos >= source.size()-1))
956
    {
957
    return source.c_str();
958
959
    }
  // current position
960
  std::string::size_type currentPos =0; // start at 0
961
962
  std::string result; // string with replacements
  // go until the the end of the string
963
  while((markerPos != std::string::npos) && (markerPos < source.size()-1))
964
965
966
967
968
    {
    // grab string from currentPos to the start of the variable
    // and add it to the result
    result += source.substr(currentPos, markerPos - currentPos);
    char endVariableMarker;     // what is the end of the variable @ or }
969
    int markerStartSize = 1;    // size of the start marker 1 or 2 or 5
970
    if(!atOnly && source[markerPos] == '$')
971
      {
972
973
974
975
976
977
      // ${var} case
      if(source[markerPos+1] == '{')
        {
        endVariableMarker = '}';
        markerStartSize = 2;
        }
978
      // $ENV{var} case
979
      else if(markerPos+4 < source.size() &&
980
              source[markerPos+4] == '{' &&
981
              !source.substr(markerPos+1, 3).compare("ENV"))
982
983
984
985
        {
        endVariableMarker = '}';
        markerStartSize = 5;
        }
986
987
988
989