samedi 30 mai 2020

Template operator overload is not picked up by linker

I have this minimal working example (I deliberately use cstdio here to keep nm output readable):

// main.cpp
#include "cstdio"
#include "foo.hpp"

int main() {
    Foo<int> foo{42};
    Foo<int> bar{42};

    bool b = foo == bar;
    printf("%d\n", b);

    return 0;
}
// foo.hpp
#pragma once

template<typename T>
struct Foo {
    Foo(T foo_) : foo{foo_} {}

    T foo;

    friend bool operator==(const Foo<T> &lhs, const Foo<T> &rhs);
};
// foo.cpp
#include "foo.hpp"

template<typename T>
bool operator==(const Foo<T> &lhs, const Foo<T> &rhs) {
    return false;
}

template struct Foo<int>;
template bool operator==(const Foo<int> &lhs, const Foo<int> &rhs);

And I build it like this:

clang --std=c++2a -lstdc++ main.cpp foo.cpp

It fails with

Undefined symbols for architecture x86_64:
  "operator==(Foo<int> const&, Foo<int> const&)", referenced from:
      _main in main-3d7fff.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

despite I explicitly instantiated operator== template.

I have rebuilt each file separately:

clang --std=c++2a -c main.cpp
clang --std=c++2a -c foo.cpp

And explored both with nm:

main.o: 0000000000000060 T Foo<int>::Foo(int)
main.o: 0000000000000090 T Foo<int>::Foo(int)
main.o:                  U operator==(Foo<int> const&, Foo<int> const&)
main.o: 0000000000000000 T _main
main.o:                  U _printf
foo.o: 0000000000000020 T Foo<int>::Foo(int)
foo.o: 0000000000000000 T Foo<int>::Foo(int)
foo.o: 0000000000000050 T bool operator==<int>(Foo<int> const&, Foo<int> const&)

And despite that two signatures look compatible to me, when I try to link this, it fails:

$ ld -lc foo.o main.o 2>&1 | c++filt
Undefined symbols for architecture x86_64:
  "operator==(Foo<int> const&, Foo<int> const&)", referenced from:
      _main in main.o
ld: symbol(short) not found for architecture x86_64

Why? How can I fix this?

Aucun commentaire:

Enregistrer un commentaire