Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clang++ makes linker fail on template classes (but it works with g++)

I have a program that works nicely with GCC, but compiling it with Clang instead makes the linker fail.

I think my issue is with template classes, so I implemented this small example.

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}
{}

When I build it with g++ Point.cpp test.cpp, it works without a problem.

But with Clang, it gives the following errors:

$ 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)

Or, using 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)

I guess my explicit instantiations in Point.h aren't good enough for Clang, but I can't figure what it wants.

like image 676
scozy Avatar asked Nov 16 '25 17:11

scozy


1 Answers

Your explicit instantiation should be where definitions are visible, so at the end of Points.cpp

From class_template#Explicit_instantiation:

An explicit instantiation definition forces instantiation of the class, struct, or union they refer to. It may appear in the program anywhere after the template definition, and for a given argument-list, is only allowed to appear once in the entire program, no diagnostic required.

like image 192
Jarod42 Avatar answered Nov 18 '25 06:11

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!