Clang ++ sprawia, że ​​linker nie działa na klasach szablonów (ale działa z g ++)

Dec 23 2020

Mam program, który dobrze współpracuje z GCC, ale skompilowanie go z Clang powoduje, że linker nie działa.

Myślę, że mój problem dotyczy klas szablonów, więc zaimplementowałem ten mały przykład.

test.cpp:

#include "Point.h"

int main()
{
    Point<int> p1;
    Point<int> p2{ 3, 6 };
}

Point.h:

#ifndef POINT_H
#define POINT_H

template<typename T>
class Point {
    T x, y;
  public:
    Point();
    Point(T, T);
};

template class Point<int>;
template class Point<float>;

#endif

Point.cpp:

#include "Point.h"

template<typename T>
Point<T>::Point()
    : x{0}, y{0}
{}

template<typename T>
Point<T>::Point(T t_x, T t_y)
    : x{t_x}, y{t_y}
{}

Kiedy go buduję g++ Point.cpp test.cpp, działa bez problemu.

Ale z Clang daje następujące błędy:

$ clang++ Point.cpp test.cpp
/usr/bin/ld: /tmp/test-8ab886.o: in function `main':
test.cpp:(.text+0x1a): undefined reference to `Point<int>::Point()'
/usr/bin/ld: test.cpp:(.text+0x2d): undefined reference to `Point<int>::Point(int, int)'
clang-11: error: linker command failed with exit code 1 (use -v to see invocation)

Lub używając lld:

$ clang++ -fuse-ld=lld Point.cpp test.cpp
ld.lld: error: undefined symbol: Point<int>::Point()
>>> referenced by test.cpp
>>>               /tmp/test-f95759.o:(main)

ld.lld: error: undefined symbol: Point<int>::Point(int, int)
>>> referenced by test.cpp
>>>               /tmp/test-f95759.o:(main)
clang-11: error: linker command failed with exit code 1 (use -v to see invocation)

Wydaje mi się, że moje jawne instancje w programie Point.hnie są wystarczająco dobre dla Clanga, ale nie mogę określić, czego chce.

Odpowiedzi

5 Jarod42 Dec 23 2020 at 07:17

Twoja jawna instancja powinna znajdować się tam, gdzie definicje są widoczne, a więc na końcu Points.cpp

Z class_template # Explicit_instantiation :

Jawna definicja instancji wymusza tworzenie instancji klasy, struktury lub unii, do której się odnoszą. Może pojawić się w programie w dowolnym miejscu po definicji szablonu, a dla danej listy argumentów może pojawić się tylko raz w całym programie, bez diagnostyki.