1

I am new to cpp and I am trying to write a simple project using cmake.

Goal: write libraries and include them into other projects. Problem: I keep getting linker errors, I do not know how to proceed.

I have written the class in a single file and things works properly, but when I split my code into libraries I get errors

#include <iostream>
#include <algorithm>
#include <vector>
#include <initializer_list>

#include "op.hpp"

using std::cout;
using std::endl;
using std::sort;
using std::vector;

using Ops::Operation;
using sort::Sorter;

int main(int argc, char **argv)
{
    int arr[] = {2, 3, 4, 2, 3, -1, 0};
    int n = sizeof(arr) / sizeof(arr[0]);
    vector<int> vec(arr, arr + n);

    for (auto a : vec)
        cout << a << '\t';
    cout << endl;

    Sorter s;
    s.sort(vec);

    for (auto a : vec)
        cout << a << '\t';
    cout << endl;
}
#include <algorithm>
#include "op.hpp"
#include <stdio.h>

namespace Ops
{
int Operation::add(const int a, const int b)
{
    return a + b;
}

} // namespace Ops

namespace sort
{
Sorter::Sorter() {}

template <typename C>
void Sorter::sort(C &c)
{
    std::sort(c.begin(), c.end());
}
} // namespace sort
namespace Ops
{
class Operation
{
public:
    int add(const int, const int);
};
} // namespace Ops

namespace sort 
{
class Sorter
{
public:
    Sorter();
    template <class C>
    void sort(C &c);
};
} // namespace sorter
cmake_minimum_required(VERSION 3.14 FATAL_ERROR)
project(testing VERSION 1.0.0)

add_library(
    op SHARED
    op.hpp
    op.cpp
)
add_executable(main main.cpp)

target_link_libraries(main PRIVATE op)

I expect the output to be the sorted vector printed I get error

Undefined symbols for architecture x86_64:
  "void sort::Sorter::sort<std::__1::vector<int, std::__1::allocator<int> > >(std::__1::vector<int, std::__1::allocator<int> >&)", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [main] Error 1
make[1]: *** [CMakeFiles/main.dir/all] Error 2
make: *** [all] Error 2
unwosu
  • 238
  • 1
  • 3
  • 10

0 Answers0