0

I tried creating a template class and get a linker error:

FAILED: untitled 
: && /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -g -arch arm64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk -mmacosx-version-min=13.2 -Wl,-search_paths_first -Wl,-headerpad_max_install_names  CMakeFiles/untitled.dir/main.cpp.o CMakeFiles/untitled.dir/new_class.cpp.o -o untitled   && :
Undefined symbols for architecture arm64:
  "void foo<double>(new_class<double> const&)", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.

my class is stored in .h and .cpp file

new_class.h

#ifndef UNTITLED__NEW_CLASS_H_
#define UNTITLED__NEW_CLASS_H_
#include <iostream>

template <typename T = double>
class new_class {
 public:
  new_class();
};

template <typename T>
void foo(const new_class<T>& nc);

#endif //UNTITLED__NEW_CLASS_H_

than new_class.cpp

#include "new_class.h"
template <typename T>
new_class<T>::new_class() = default;

template<typename T>
void foo(const new_class<T>& nc) {}

template class new_class<double>;

main.cpp

#include "new_class.h"

int main() {
  new_class new_class;
  foo(new_class);
  return 0;
}

finally my Cmake

cmake_minimum_required(VERSION 3.23)
project(untitled)

set(CMAKE_CXX_STANDARD 17)

add_executable(untitled main.cpp new_class.cpp)

I did all Stackoverflow suggested, like add new_class.cpp to Cmake file, add template class new_class<double> to new_class.cpp but I can't understand why linker can't find implementation of foo function

Rumata
  • 1

0 Answers0