Sun Studio 12: C++ User's Guide

6.7.7 Building Multiple Programs Using Templates in the Same Directory

If you are building more than one program or library by specifying -instances=extern, it’s advisable to build them in separate directories. If you want to build in the same directory then you should clean the repository between the different builds. This avoids any unpredictable errors. For more information see 7.4.4 Sharing Template Repositories.

Consider the following example with make files a.cc, b.cc, x.h, and x.cc. Note that this example is meaningful only if you specify -instances=extern:


........
Makefile
........
CCC = CC

all: a b

a:
    $(CCC) -I. -instances=extern -c a.cc
    $(CCC) -instances=extern -o a a.o

b:
    $(CCC) -I. -instances=extern -c b.cc
    $(CCC) -instances=extern -o b b.o

clean:
    /bin/rm -rf SunWS_cache *.o a b

...
x.h
...
template <class T> class X {
public:
  int open();
  int create();
  static int variable;
};

...
x.cc
...
template <class T> int X<T>::create() {
  return variable;
}

template <class T> int X<T>::open() {
  return variable;
}

template <class T> int X<T>::variable = 1;

...
a.cc
...
#include "x.h"

int main()
{
  X<int> temp1;

  temp1.open();
  temp1.create();
}

...
b.cc
...
#include "x.h"

int main()
{
  X<int> temp1;

  temp1.create();
}

If you build both a and b, add a make clean between the two builds. The following commands result in an error:


example% make a
example% make b

The following commands will not produce any error:


example% make a
example% make clean
example% make b