cmMakefile.cxx 44 KB
Newer Older
1
2
/*=========================================================================

3
  Program:   CMake - Cross-Platform Makefile Generator
4
5
6
7
8
  Module:    $RCSfile$
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

9
10
  Copyright (c) 2002 Kitware, Inc., Insight Consortium.  All rights reserved.
  See Copyright.txt or http://www.cmake.org/HTML/Copyright.html 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->AddDefaultDefinitions();
57
58
}

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

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


78
79
cmMakefile::~cmMakefile()
{
80
81
82
83
84
  for(std::vector<cmSourceFile*>::iterator i = m_SourceFiles.begin();
      i != m_SourceFiles.end(); ++i)
    {
    delete *i;
    }
85
  for(unsigned int i=0; i < m_UsedCommands.size(); i++)
86
    {
87
    delete m_UsedCommands[i];
88
    }
89
90
91
92
93
94
95
96
  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
97
  std::list<cmFunctionBlocker *>::iterator pos;
Bill Hoffman's avatar
Bill Hoffman committed
98
  for (pos = m_FunctionBlockers.begin(); 
Ken Martin's avatar
Ken Martin committed
99
       pos != m_FunctionBlockers.end(); ++pos)
Bill Hoffman's avatar
Bill Hoffman committed
100
101
102
103
    {
    cmFunctionBlocker* b = *pos;
    delete b;
    }
Ken Martin's avatar
Ken Martin committed
104
  m_FunctionBlockers.clear();
105
106
}

107
void cmMakefile::PrintStringVector(const char* s, const std::vector<std::string>& v) const
108
109
{
  std::cout << s << ": ( \n";
110
  for(std::vector<std::string>::const_iterator i = v.begin();
111
112
113
114
115
      i != v.end(); ++i)
    {
    std::cout << (*i).c_str() << " ";
    }
  std::cout << " )\n";
116
117
118
119
}


// call print on all the classes in the makefile
120
void cmMakefile::Print() const
121
{
122
  // print the class lists
123
  std::cout << "classes:\n";
124

125
126
127
128
129
130
131
  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
132
133
134
135
136
137
  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;
138
139
  std::cout << " m_cmCurrentDirectory; " << 
    m_cmCurrentDirectory.c_str() << std::endl;
Ken Martin's avatar
Ken Martin committed
140
141
142
143
  std::cout << " m_cmStartDirectory; " << 
    m_cmStartDirectory.c_str() << std::endl;
  std::cout << " m_cmHomeDirectory; " << 
    m_cmHomeDirectory.c_str() << std::endl;
144
  std::cout << " m_ProjectName; " <<  m_ProjectName.c_str() << std::endl;
145
146
147
  this->PrintStringVector("m_SubDirectories ", m_SubDirectories); 
  this->PrintStringVector("m_IncludeDirectories;", m_IncludeDirectories);
  this->PrintStringVector("m_LinkDirectories", m_LinkDirectories);
148
149
150
151
152
  for( std::vector<cmSourceGroup>::const_iterator i = m_SourceGroups.begin();
       i != m_SourceGroups.end(); ++i)
    {
    i->Print();
    }
153
154
}

155
156
bool cmMakefile::CommandExists(const char* name) const
{
157
  return m_LocalGenerator->GetGlobalGenerator()->GetCMakeInstance()->CommandExists(name);
158
}
159
160

bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff)
Ken Martin's avatar
Ken Martin committed
161
{
162
  bool result = true;
163
  // quick return if blocked
164
  if(this->IsFunctionBlocked(lff))
165
    {
166
167
    // No error.
    return result;
168
    }
169
  std::string name = lff.m_Name;
170
  // execute the command
171
172
173
  cmCommand *rm = 
    m_LocalGenerator->GetGlobalGenerator()->GetCMakeInstance()->GetCommand(name.c_str());
  if(rm)
Ken Martin's avatar
Ken Martin committed
174
175
176
177
178
179
180
181
182
183
    {
    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())
        {
184
        if(!usedCommand->InvokeInitialPass(lff.m_Arguments))
185
          {
186
187
188
189
190
          cmOStringStream error;
          error << "Error in cmake code at\n"
                << lff.m_FilePath << ":" << lff.m_Line << ":\n"
                << usedCommand->GetError();
          cmSystemTools::Error(error.str().c_str());
191
          result = false;
Ken Martin's avatar
Ken Martin committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
          }
        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;
      }
    }
  else
    {
210
211
212
213
214
    cmOStringStream error;
    error << "Error in cmake code at\n"
          << lff.m_FilePath << ":" << lff.m_Line << ":\n"
          << "Unknown CMake command \"" << lff.m_Name.c_str() << "\".";
    cmSystemTools::Error(error.str().c_str());
215
    result = false;
Ken Martin's avatar
Ken Martin committed
216
    }
217
218
  
  return result;
Ken Martin's avatar
Ken Martin committed
219
220
}

221
// Parse the given CMakeLists.txt file into a list of classes.
Ken Martin's avatar
Ken Martin committed
222
223
// Reads in current CMakeLists file and all parent CMakeLists files
// executing all inherited commands in the parents
Anonymous's avatar
Anonymous committed
224
225
226
227
228
229
230
//
//   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)
231
{
232
233
234
235
236
  // 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
237
238
  if (filename)
    {
Bill Hoffman's avatar
Bill Hoffman committed
239
240
241
242
    if(m_cmCurrentListFile != filename)
      {
      m_cmCurrentListFile = filename;
      }
243
    // loop over current function blockers and record them
Bill Hoffman's avatar
Bill Hoffman committed
244
    std::list<cmFunctionBlocker *>::iterator pos;
245
246
247
248
249
    for (pos = m_FunctionBlockers.begin(); 
         pos != m_FunctionBlockers.end(); ++pos)
      {
      originalBlockers.insert(*pos);
      }
250
    }
251
  
Anonymous's avatar
Anonymous committed
252
253
254
255
  // 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)
256
    {
Anonymous's avatar
Anonymous committed
257
258
259
260
      // 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 != "")
261
262
        {
          std::string srcdir = m_cmCurrentDirectory;
263
264
          std::string bindir = m_CurrentOutputDirectory;

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

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

270
271
272
          // if not found, oops
          if(pos == std::string::npos)
            {
273
            cmSystemTools::Error("Trailing slash not found");
274
            }
275

276
          this->ReadListFile(parentList.c_str());
277

278
279
280
281
          // restore the current directory
          m_cmCurrentDirectory = srcdir;
          m_CurrentOutputDirectory = bindir;    
        }
282
    }
Ken Martin's avatar
Ken Martin committed
283
284
285

  // are we at the start CMakeLists file or are we processing a parent 
  // lists file
Anonymous's avatar
Anonymous committed
286
287
288
  //
  //   this might, or might not be true, irrespective if we are
  //   off looking at an external makefile.
Ken Martin's avatar
Ken Martin committed
289
  m_Inheriting = (m_cmCurrentDirectory != m_cmStartDirectory);
Ken Martin's avatar
Ken Martin committed
290
                    
291
  // Now read the input file
Anonymous's avatar
Anonymous committed
292
293
294
  const char *filenametoread= filename;

  if( external)
295
    {
Anonymous's avatar
Anonymous committed
296
    filenametoread= external;
297
    }
298
299
300
301
302
303
  // try to see if the list file is the top most
  // list file for a project, and if it is, then it
  // must have a project command.   If there is not
  // one, then cmake will provide one via the 
  // cmListFileCache class.
  bool requireProjectCommand = false;
304
  if(!external && m_cmCurrentDirectory == m_cmHomeDirectory)
305
306
307
308
309
310
311
312
    {
    if(cmSystemTools::LowerCase(
         cmSystemTools::GetFilenameName(filename)) == "cmakelists.txt")
      {
      requireProjectCommand = true;
      }
    }
      
313
  cmListFile* lf = 
314
315
    cmListFileCache::GetInstance()->GetFileCache(filenametoread,
                                                 requireProjectCommand);
316
  if(!lf)
317
318
319
    {
    return false;
    }
320
321
  // add this list file to the list of dependencies
  m_ListFiles.push_back( filenametoread);
322
323
  const size_t numberFunctions = lf->m_Functions.size();
  for(size_t i =0; i < numberFunctions; ++i)
324
    {
325
    this->ExecuteCommand(lf->m_Functions[i]);
326
    }
Ken Martin's avatar
Ken Martin committed
327
328
329
330
331

  // 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
332
    std::list<cmFunctionBlocker *>::iterator pos;
Ken Martin's avatar
Ken Martin committed
333
334
335
    for (pos = m_FunctionBlockers.begin(); 
         pos != m_FunctionBlockers.end(); ++pos)
      {
336
337
338
339
340
341
      // 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
342
343
344
      }
    }
  
345
346
  return true;
}
347

348

349
void cmMakefile::AddCommand(cmCommand* wg)
350
{
351
  m_LocalGenerator->GetGlobalGenerator()->GetCMakeInstance()->AddCommand(wg);
352
353
354
}

  // Set the make file 
Ken Martin's avatar
Ken Martin committed
355
void cmMakefile::SetLocalGenerator(cmLocalGenerator* lg)
356
{
Ken Martin's avatar
Ken Martin committed
357
  m_LocalGenerator = lg;
358
359
}

360
void cmMakefile::FinalPass()
361
362
{
  // do all the variable expansions here
363
  this->ExpandVariables();
364

365
  // give all the commands a chance to do something
366
  // after the file has been parsed before generation
367
368
  for(std::vector<cmCommand*>::iterator i = m_UsedCommands.begin();
      i != m_UsedCommands.end(); ++i)
369
370
    {
    (*i)->FinalPass();
371
    }
372
373
374
375

}

  // Generate the output file
376
void cmMakefile::ConfigureFinalPass()
377
378
{
  this->FinalPass();
379
380
381
  const char* versionValue
    = this->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION");
  bool oldVersion = (!versionValue || atof(versionValue) < 1.4);
382
  // merge libraries
383
  
384
385
386
  for (cmTargets::iterator l = m_Targets.begin();
       l != m_Targets.end(); l++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
387
    l->second.GenerateSourceFilesFromSourceLists(*this);
388
389
390
391
392
    // pick up any LINK_LIBRARIES that were added after the target
    if(oldVersion)
      {
      this->AddGlobalLinkInformation(l->first.c_str(), l->second);
      }
393
    l->second.AnalyzeLibDependencies(*this);
394
    }
395
396
}

397

398
399
void cmMakefile::AddCustomCommand(const char* source,
                                  const char* command,
Ken Martin's avatar
Ken Martin committed
400
                                  const std::vector<std::string>& commandArgs,
401
                                  const std::vector<std::string>& depends,
402
                                  const std::vector<std::string>& outputs,
403
404
                                  const char *target,
                                  const char *comment) 
405
{
406
407
408
  // find the target, 
  if (m_Targets.find(target) != m_Targets.end())
    {
409
410
411
    std::string expandC = command;
    this->ExpandVariablesInString(expandC);
    std::string c = cmSystemTools::EscapeSpaces(expandC.c_str());
Ken Martin's avatar
Ken Martin committed
412
413

    std::string combinedArgs;
Bill Hoffman's avatar
Bill Hoffman committed
414
    unsigned int i;
Ken Martin's avatar
Ken Martin committed
415
416
417
418
419
420
421
422
    
    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);
423
424
425
426
    if ( comment && comment[0] )
      {
      cc.SetComment(comment);
      }
427
    m_Targets[target].GetCustomCommands().push_back(cc);
428
429
    std::string cacheCommand = command;
    this->ExpandVariablesInString(cacheCommand);
Ken Martin's avatar
Ken Martin committed
430
    if(this->GetCacheManager()->GetCacheValue(cacheCommand.c_str()))
431
432
      {
      m_Targets[target].AddUtility(
Ken Martin's avatar
Ken Martin committed
433
        this->GetCacheManager()->GetCacheValue(cacheCommand.c_str()));
434
      }
435
    }
436
}
437

438
void cmMakefile::AddCustomCommand(const char* source,
439
                                  const char* command,
Ken Martin's avatar
Ken Martin committed
440
                                  const std::vector<std::string>& commandArgs,
441
                                  const std::vector<std::string>& depends,
442
443
                                  const char* output, 
                                  const char *target) 
444
{
445
446
  std::vector<std::string> outputs;
  outputs.push_back(output);
447
  this->AddCustomCommand(source, command, commandArgs, depends, outputs, target);
448
449
450
451
452
453
454
455
}

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

456

457
void cmMakefile::AddLinkLibrary(const char* lib, cmTarget::LinkLibraryType llt)
458
459
{
  m_LinkLibraries.push_back(
460
          std::pair<std::string, cmTarget::LinkLibraryType>(lib,llt));
461
462
463
464
465
}

void cmMakefile::AddLinkLibraryForTarget(const char *target,
                                         const char* lib, 
                                         cmTarget::LinkLibraryType llt)
466
467
468
{ 
  cmTargets::iterator i = m_Targets.find(target);
  if ( i != m_Targets.end())
469
    {
470
    i->second.AddLinkLibrary( *this, target, lib, llt );
471
    }
Berk Geveci's avatar
Berk Geveci committed
472
473
474
475
  else
    {
    cmSystemTools::Error("Attempt to add link libraries to non-existant target: ",  target, " for lib ", lib);
    }
476
477
}

478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
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);
    }
}

493
494
void cmMakefile::AddLinkLibrary(const char* lib)
{
495
  this->AddLinkLibrary(lib,cmTarget::GENERAL);
496
497
498
499
}

void cmMakefile::AddLinkDirectory(const char* dir)
{
500
501
502
503
  // 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.
504
505
506
507
508
509
510
511
512
513
514
515
516
  
  // 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
517
    {
518
519
520
521
522
    if(std::find(m_LinkDirectories.begin(),
                 m_LinkDirectories.end(), dir) == m_LinkDirectories.end())
      {
      m_LinkDirectories.push_back(dir);
      }
523
    }
524
525
526
527
528
529
530
}

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

531
void cmMakefile::AddIncludeDirectory(const char* inc, bool before)
532
{
533
534
535
536
537
538
539
  // 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())
    {
540
541
542
543
544
545
546
547
548
    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);
      }
549
    }
550
551
}

552

553
554
void cmMakefile::AddDefinition(const char* name, const char* value)
{
555
556
557
558
  if (!value )
    {
    return;
    }
559
  m_Definitions.erase( DefinitionMap::key_type(name));
560
561
  m_Definitions.insert(DefinitionMap::value_type(name, value));
}
562

563
564
565
566
567

void cmMakefile::AddCacheDefinition(const char* name, const char* value, 
                                    const char* doc,
                                    cmCacheManager::CacheEntryType type)
{
Ken Martin's avatar
Ken Martin committed
568
  this->GetCacheManager()->AddCacheEntry(name, value, doc, type);
569
570
571
572
  this->AddDefinition(name, value);
}


573
574
575
576
void cmMakefile::AddDefinition(const char* name, bool value)
{
  if(value)
    {
577
    m_Definitions.erase( DefinitionMap::key_type(name));
578
579
580
581
    m_Definitions.insert(DefinitionMap::value_type(name, "ON"));
    }
  else
    {
582
    m_Definitions.erase( DefinitionMap::key_type(name));
583
584
585
    m_Definitions.insert(DefinitionMap::value_type(name, "OFF"));
    }
}
586

587
588
589

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

594
595
596
597
598
void cmMakefile::RemoveDefinition(const char* name)
{
  m_Definitions.erase(DefinitionMap::key_type(name));
}

599
600
601
602
603
void cmMakefile::SetProjectName(const char* p)
{
  m_ProjectName = p;
}

604
605
606

void cmMakefile::AddGlobalLinkInformation(const char* name, cmTarget& target)
{
607
608
609
  // for these targets do not add anything
  switch(target.GetType())
    {
Andy Cedilnik's avatar
Andy Cedilnik committed
610
611
612
613
    case cmTarget::UTILITY: 
    case cmTarget::INSTALL_FILES: 
    case cmTarget::INSTALL_PROGRAMS: 
      return;
Brad King's avatar
Brad King committed
614
    default:;
615
    }
616
617
618
619
620
621
  std::vector<std::string>::iterator j;
  for(j = m_LinkDirectories.begin();
      j != m_LinkDirectories.end(); ++j)
    {
    target.AddLinkDirectory(j->c_str());
    }
622
  target.MergeLinkLibraries( *this, name, m_LinkLibraries );
623
624
625
}


Yves Starreveld's avatar
   
Yves Starreveld committed
626
void cmMakefile::AddLibrary(const char* lname, int shared,
627
                            const std::vector<std::string> &srcs)
628
629
{
  cmTarget target;
Yves Starreveld's avatar
   
Yves Starreveld committed
630
631
632
633
634
635
636
637
638
639
640
641
642
643
  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);
    }
644

Bill Hoffman's avatar
Bill Hoffman committed
645
646
647
  // Clear its dependencies. Otherwise, dependencies might persist
  // over changes in CMakeLists.txt, making the information stale and
  // hence useless.
648
  target.ClearDependencyInformation( *this, lname );
Bill Hoffman's avatar
Bill Hoffman committed
649
  
Ken Martin's avatar
Ken Martin committed
650
  target.SetInAll(true);
651
  target.GetSourceLists() = srcs;
652
  this->AddGlobalLinkInformation(lname, target);
653
  m_Targets.insert(cmTargets::value_type(lname,target));
654
655

  // Add an entry into the cache 
656
657
  std::string libPath = lname;
  libPath += "_CMAKE_PATH";
Ken Martin's avatar
Ken Martin committed
658
  this->GetCacheManager()->
659
    AddCacheEntry(libPath.c_str(),
660
661
                  this->GetCurrentOutputDirectory(),
                  "Path to a library", cmCacheManager::INTERNAL);
662
663
664
665

  // Add an entry into the cache
  std::string ltname = lname;
  ltname += "_LIBRARY_TYPE";
Yves Starreveld's avatar
   
Yves Starreveld committed
666
667
668
  switch (shared)
    {
    case 0:
Ken Martin's avatar
Ken Martin committed
669
      this->GetCacheManager()->AddCacheEntry(ltname.c_str(),"STATIC",
670
671
                      "Whether a library is static, shared or module.",
                      cmCacheManager::INTERNAL);
Yves Starreveld's avatar
   
Yves Starreveld committed
672
673
      break;
    case 1:
Ken Martin's avatar
Ken Martin committed
674
      this->GetCacheManager()->
675
676
677
678
        AddCacheEntry(ltname.c_str(),
                      "SHARED",
                      "Whether a library is static, shared or module.",
                      cmCacheManager::INTERNAL);
Yves Starreveld's avatar
   
Yves Starreveld committed
679
680
      break;
    case 2:
Ken Martin's avatar
Ken Martin committed
681
      this->GetCacheManager()->
682
683
684
685
        AddCacheEntry(ltname.c_str(),
                      "MODULE",
                      "Whether a library is static, shared or module.",
                      cmCacheManager::INTERNAL);
Yves Starreveld's avatar
   
Yves Starreveld committed
686
687
      break;
    default:
Ken Martin's avatar
Ken Martin committed
688
      this->GetCacheManager()->
689
690
691
692
        AddCacheEntry(ltname.c_str(),
                      "STATIC",
                      "Whether a library is static, shared or module.",
                      cmCacheManager::INTERNAL);
Yves Starreveld's avatar
   
Yves Starreveld committed
693
    }
694
695
696
697
}

void cmMakefile::AddExecutable(const char *exeName, 
                               const std::vector<std::string> &srcs)
698
699
700
701
702
703
704
{
  this->AddExecutable(exeName,srcs,false);
}

void cmMakefile::AddExecutable(const char *exeName, 
                               const std::vector<std::string> &srcs,
                               bool win32)
705
{
706
  cmTarget target;
707
708
709
710
711
712
713
714
  if (win32)
    {
    target.SetType(cmTarget::WIN32_EXECUTABLE);
    }
  else
    {
    target.SetType(cmTarget::EXECUTABLE);
    }
Ken Martin's avatar
Ken Martin committed
715
  target.SetInAll(true);
716
  target.GetSourceLists() = srcs;
717
  this->AddGlobalLinkInformation(exeName, target);
718
719
  m_Targets.insert(cmTargets::value_type(exeName,target));
  
720
721
  
  // Add an entry into the cache 
722
723
  std::string exePath = exeName;
  exePath += "_CMAKE_PATH";
Ken Martin's avatar
Ken Martin committed
724
  this->GetCacheManager()->
725
    AddCacheEntry(exePath.c_str(),
726
727
                  this->GetCurrentOutputDirectory(),
                  "Path to an executable", cmCacheManager::INTERNAL);
728
729
}

730

731
void cmMakefile::AddUtilityCommand(const char* utilityName,
732
                                   const char* command,
733
                                   const char* arguments,
734
735
736
                                   bool all)
{
  std::vector<std::string> empty;
737
  this->AddUtilityCommand(utilityName,command,arguments,all,
738
739
740
741
742
                          empty,empty);
}

void cmMakefile::AddUtilityCommand(const char* utilityName,
                                   const char* command,
743
                                   const char* arguments,
744
745
746
                                   bool all,
                                   const std::vector<std::string> &dep,
                                   const std::vector<std::string> &out)
747
748
749
{
  cmTarget target;
  target.SetType(cmTarget::UTILITY);
750
  target.SetInAll(all);
751
  cmCustomCommand cc(utilityName, command, arguments, dep, out);
752
753
754
755
  target.GetCustomCommands().push_back(cc);
  m_Targets.insert(cmTargets::value_type(utilityName,target));
}

756
757
758
759
760
761
762
763
764
765
766
767
768
769
cmSourceGroup* cmMakefile::GetSourceGroup(const char* name)
{
  // 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)
      {
      return &(*sg);
      }
    }
  return 0;
}
770

771
772
773
774
775
776
777
778
779
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)
      {
780
781
782
783
784
785
      if ( regex )
        {
        // 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);
        }
786
787
788
789
790
791
792
      return;
      }
    }
  
  // The group doesn't exist.  Add it.
  m_SourceGroups.push_back(cmSourceGroup(name, regex));
}
793
794
795
796
797

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

799

Ken Martin's avatar
Ken Martin committed
800
801
802
803
804
// 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)
805
{
Ken Martin's avatar
Ken Martin committed
806
807
808
809
810
811
  // 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)
812
    {
Ken Martin's avatar
Ken Martin committed
813
    return parentFile;
814
    }
Ken Martin's avatar
Ken Martin committed
815
816
817
818
  listsDir = listsDir.substr(0, pos);
  
  // if we are in the home directory then stop, return 0
  if(m_cmHomeDirectory == listsDir)
819
    {
Ken Martin's avatar
Ken Martin committed
820
    return parentFile;
821
    }
Ken Martin's avatar
Ken Martin committed
822
823
824
825
826
827
828
829
830
831
832
833
834
  
  // 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";
835
  while(!cmSystemTools::FileExists(parentFile.c_str()))
836
    {
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
    // 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";
853
    }
854

Ken Martin's avatar
Ken Martin committed
855
  return parentFile;
856
857
}

858
859
860
// expance CMAKE_BINARY_DIR and CMAKE_SOURCE_DIR in the
// include and library directories.

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

881
bool cmMakefile::IsOn(const char* name) const
882
883
884
885
886
{
  const char* value = this->GetDefinition(name);
  return cmSystemTools::IsOn(value);
}

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


898

899
const char *cmMakefile::ExpandVariablesInString(std::string& source) const
900
{
901
  return this->ExpandVariablesInString(source, false);
902
903
}

904
const char *cmMakefile::ExpandVariablesInString(std::string& source,
905
906
                                                bool escapeQuotes,
                                                bool atOnly) const
907
{
908
  // This method replaces ${VAR} and @VAR@ where VAR is looked up
909
  // with GetDefinition(), if not found in the map, nothing is expanded.
910
911
  // It also supports the $ENV{VAR} syntax where VAR is looked up in
  // the current environment variables.
912

913
  // start by look for $ or @ in the string
914
915
916
917
918
919
920
921
922
  std::string::size_type markerPos;
  if(atOnly)
    {
    markerPos = source.find_first_of("@");
    }
  else
    {
    markerPos = source.find_first_of("$@");
    }
923
924
925
  // 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))
926
    {
927
    return source.c_str();
928
929
    }
  // current position
930
  std::string::size_type currentPos =0; // start at 0
931
932
  std::string result; // string with replacements
  // go until the the end of the string
933
  while((markerPos != std::string::npos) && (markerPos < source.size()-1))
934
935
936
937
938
    {
    // 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 }
939
    int markerStartSize = 1;    // size of the start marker 1 or 2 or 5
940
    if(!atOnly && source[markerPos] == '$')
941
      {
942
943
944
945
946
947
      // ${var} case
      if(source[markerPos+1] == '{')
        {
        endVariableMarker = '}';
        markerStartSize = 2;
        }
948
      // $ENV{var} case
949
      else if(markerPos+4 < source.size() &&
950
              source[markerPos+4] == '{' &&
951
              !source.substr(markerPos+1, 3).compare("ENV"))
952
953
954
955
        {
        endVariableMarker = '}';
        markerStartSize = 5;
        }
956
957
958
959
960
961
962
      else
        {
        // bogus $ with no { so add $ to result and move on
        result += '$'; // add bogus $ back into string
        currentPos = markerPos+1; // move on
        endVariableMarker = ' '; // set end var to space so we can tell bogus
        }
963
      }
964
965
966
967
968
    else
      {
      // @VAR case
      endVariableMarker = '@';
      }
969
    // if it was a valid variable (started with @ or ${ or $ENV{ )
970
971
972
973
    if(endVariableMarker != ' ')
      {
      markerPos += markerStartSize; // move past marker
      // find the end variable marker starting at the markerPos
974
      std::string::size_type endVariablePos =
975
976
977
978
979
980
981
982
983
984
        source.find(endVariableMarker, markerPos);
      if(endVariablePos == std::string::npos)
        {
        // no end marker found so add the bogus start
        if(endVariableMarker == '@')
          {
          result += '@';
          }
        else
          {
985
          result += (markerStartSize == 5 ? "$ENV{" : "${");
986
987
988
989
990
991
992
          }
        currentPos = markerPos;
        }
      else
        {
        // good variable remove it
        std::string var = source.substr(markerPos, endVariablePos - markerPos);
993
994
        bool found = false;
        if (markerStartSize == 5) // $ENV{
995
          {
996
          char *ptr = getenv(var.c_str());
997
          if (ptr)
998
            {
999
1000
            if (escapeQuotes)
              {