0

I simplify the problem. I wanna know why this can't compile:

Error message: undefined reference to 'Foo<int>::j'

a.h

#pragma once
template<typename T>  
class Foo{
    public:
        int bar(){
            return j;
        }
    private:
        static int j;
};

a.cpp

#include "a.h"
template<typename T>
int Foo<T>::j = 3;

main.cpp

#include "a.h"
#include <iostream>
using namespace std;

    int main() {
      Foo<int> f;
      cout << f.bar();
      return 0;
    }
Rick
  • 7,007
  • 2
  • 49
  • 79

1 Answers1

0

Templates are the cause.

template<typename T>
int Foo<T>::j = 3;

doesn't get resolved for main.cpp as it has no information about a.cpp. And as for a.cpp it doesn't create Foo as it isn't used there.

For the system to work, you'd need to add

int Foo<int>::j = 3;

to a.cpp or

template<typename T>
int Foo<T>::j = 3;

to main.cpp.


On the side note, maybe new usage of inline keyword in C++17 i what you are looking for.

John Cvelth
  • 522
  • 1
  • 6
  • 19