0

There is an error when including "x.h" below from multiple C++ source files.

x.cpp:(.text+0x0): multiple definition of `void f(A&, B const&)'
/tmp/ccdXc4Sz.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status

What happens here? How can it be rewritten to work?

x.h

#pragma once

#include <iostream>

struct B
{
    int x, y;
};

struct A
{
  template <class T>
  friend void f(A& a, const T& t);
private:
  int x {0};
};

template <class T>
void f(A& a, const T& t) { std::cout << a.x++ << ": " << t << std::endl; } 

template <>
void f(A& a, const B& b) { std::cout << a.x++ << ": " << b.x << "," << b.y << std::endl; }

main.cpp

#include "x.h"
int main()
{
    A a;
    B b;
    f(a, b);
    return 0;
}

x.cpp

#include "x.h"
Evgeny
  • 2,121
  • 1
  • 20
  • 31

1 Answers1

2

Specialized templated function is not template anymore, it should be treated as normal global function. So, place it to .cpp file, or declare as static or inline.

– answer by Alex F

anatolyg
  • 26,506
  • 9
  • 60
  • 134