Undefined reference to static vector

Hi all! First post here :)

I'm trying to create a class that creates and stores objects of type T in a static vector, and returns a reference to that object so I can use it in main(), as shown in the code below:


internvect.h:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template<class T>
class InternVect
 {
   protected:
   
   	InternVect() { }
   	
   	static std::vector<T> vAll;
   	
   public:
   
  	static T& create() {
		vAll.push_back(T());
		return vAll.back();
	  }
 };




main_tman.cpp:
1
2
3
4
5
6
7
8
9
#include "internvect.h"
int main ()
 {
	int &i = InternVect<int>::create();
	
	std::cout<<i<<std::endl;
	
 	return 0;
 }



I am getting the following error:

g++-10 -I inc -I ../../inc src/main_tman.cpp -o bin/out
/usr/bin/ld: /tmp/ccoOzb7F.o: in function `InternVect<int>::create()':
main_tman.cpp:(.text._ZN10InternVectIiE6createEv[_ZN10InternVectIiE6createEv]+0x2c): undefined reference to `InternVect<int>::vAll'
/usr/bin/ld: main_tman.cpp:(.text._ZN10InternVectIiE6createEv[_ZN10InternVectIiE6createEv]+0x38): undefined reference to `InternVect<int>::vAll'
collect2: error: ld returned 1 exit status
make: *** [Makefile:15: compile] Error 1

Can anyone tell me what am I missing, or a better way to do it?

Thanks!
Dean

Last edited on
You need an implementation file to actually instantiate the vector:

1
2
3
4
5
// internvect.cpp

#include "internvect.h"

template<class T> std::vector<T> InternVect<T>::vAll;


EDIT: You may be able to put that statement in the header file after the class definition, although I'm not entirely sure about that.
Last edited on
Thanks for your help! It actually worked only when placed at the end of the header file, not with a source file.

Dean
Topic archived. No new replies allowed.