Order of linking

Do you think, that the order of object files at linking is not a significant issue? Well, check this small project, and decide it yourself.


// file: t.h
template <class T>
T t(const T&)
{
    return s;
}

// file: a.cpp
#include "t.h"
static int s = 2;

int g()
{
    return t(1);
}

// file: b.cpp
#include "t.h"
static int s = 1;

int h()
{
    return t(1);
}

// file: main.cpp
#include <iostream>

extern int g();
extern int h();

int main()
{
    std::cout << g() << std::endl;
    std::cout << h() << std::endl;
    return 0;
}

// g++ main.cpp a.cpp b.cpp
// 2 2

// g++ main.cpp b.cpp a.cpp
// 1 1

Greedy instantiation: the compiler finds the first instance of the template and drop all the other instances. Of course, the linker does not know the content of the template, so the other instances might be different...