0

Having issues with linking a template header when building a project with Bazel. The linking works for the main.cpp file but not for the hello_test.cpp file. For the BinaryTree class there is no other file than the BinaryTree.h.

Getting the following error

hello_test.pic.o:hello_test.cpp:function BinaryTreeTest::BinaryTreeTest(): error: undefined reference to 'BinaryTree<int>::BinaryTree()'
collect2: error: ld returned 1 exit status

Found this issue, but shouldn't I get the same error for main.cpp and hello_test.cpp?

"Undefined reference to" template class constructor

BUILD

cc_library(
    name = "binary-tree",
    hdrs = ["BinaryTree.h"]
)

cc_binary(
  name = "main",
  srcs = ["main.cpp"],
  deps = [":binary-tree"]
)

cc_test(
  name = "hello_test",
  srcs = ["hello_test.cpp"],
  deps = ["@com_google_googletest//:gtest_main", ":binary-tree"],
)

BinaryTree.h

template <typename T>
class BinaryTree{
public:
    T value;
    BinaryTree<T> *r = nullptr, *l = nullptr;
    BinaryTree();
    BinaryTree(T value_, BinaryTree* r_ = nullptr, BinaryTree* l_ = nullptr) : value(value_), r(r_), l(l_) {}
};

main.cpp

#include "BinaryTree.h"

int main() {
    auto a = BinaryTree<int>(1)
}

hello_test.cpp

#include <gtest/gtest.h>
#include "BinaryTree.h"

class BinaryTreeTest : public ::testing::Test {
  public:
    void SetUp() override {
      i1 = BinaryTree<int>(1);
    }

    BinaryTree<int> i1;
};

TEST_F(BinaryTreeTest, Tree) {
  EXPECT_EQ(i1.value, 1);
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
Linor
  • 55
  • 1
  • 5
  • 3
    You need a default constructor. You've declared it but haven't defined it. – Mat Sep 06 '22 at 13:37
  • _"shouldn't I get the same error for main.cpp"_? Why do you think this? Is main.cpp using the missing `BinaryTreeTest::BinaryTreeTest()`? – Drew Dormann Sep 06 '22 at 13:39

0 Answers0