Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple definitions of a function template

Suppose a header file defines a function template. Now suppose two implementation files #include this header, and each of them has a call to the function template. In both implementation files the function template is instantiated with the same type.

// header.hh
template <typename T>
void f(const T& o)
{
    // ...
}

// impl1.cc
#include "header.hh"

void fimpl1()
{
    f(42);
}

// impl2.cc
#include "header.hh"

void fimpl2()
{
    f(24);
}

One may expect the linker would complain about multiple definitions of f(). Specifically, if f() wouldn't be a template then that would indeed be the case.

  • How come the linker doesn't complain about multiple definitions of f()?
  • Is it specified in the standard that the linker must handle this situation gracefully? In other words, can I always count on programs similar to the above to compile and link?
  • If the linker can be clever enough to disambiguate a set of function template instantiations, why can't it do the same for regular functions, given they are identical as is the case for instantiated function templates?
like image 839
wilhelmtell Avatar asked Oct 24 '08 23:10

wilhelmtell


1 Answers

In order to support C++, the linker is smart enough to recognize that they are all the same function and throws out all but one.

EDIT: clarification: The linker doesn't compare function contents and determine that they are the same. Templated functions are marked as such and the linker recognizes that they have the same signatures.

like image 52
Ferruccio Avatar answered Sep 17 '22 23:09

Ferruccio