1

Recently, I struggled a bit with variable templates in C++ and found something that I do not understand. Suppose you have two global variables a and b which are declared as extern in a header file. The difference between those two is, that b is a variable template and a is not. Now, the thing I do not understand is, that a does need a definition but b does not.
So my question is, why does b need no definition but a does or rather why does the linker know, where b is defined? Can I explicitly define b? If yes, where and how?
Maybe I am doing something wrong, but the code compiles, links and runs correctly with the VC++ 2017 compiler if I test it.
Here is the related code:

// header.hpp
#pragma once

extern int a;

template<typename T>
extern T b;

// source.cpp    
#include "header.hpp"

int a; // definition of a, but definition of b is missing

// main.cpp
#include "header.hpp"

int main()
{
    a = 1;
    b<int> = 1;
    return 0;
}

0 Answers0