0

So maybe there's some obvious error in my code that I can't see, but I've been struggling it almost an hour.

This is my working directory:

├── main1.cpp
├── main2.cpp
├── utils.cpp
└── utils.h


The content of the files are

utils.h:

#include <vector>

template <typename T>
void vector_remove(std::vector<T>& v, const T& e);
void vector_remove_int(std::vector<int>& v, const int& e);

utils.cpp:

#include "utils.h"
#include <algorithm>

template <typename T>
void vector_remove(std::vector<T>& v, const T& e)
{
    auto it = find(v.begin(), v.end(), e);
    v.erase(it);
}

void vector_remove_int(std::vector<int>& v, const int& e)
{
    auto it = find(v.begin(), v.end(), e);
    v.erase(it);
}

main1.cpp:

#include "utils.h"
#include <vector>

int main()
{
    std::vector<int> x { 1, 2, 3 };
    vector_remove(x, 1);
}


main2.cpp:

#include "utils.h"
#include <vector>

int main()
{
    std::vector<int> x { 1, 2, 3 };
    vector_remove_int(x, 1);
}


Alright, when I run g++ main2.cpp utils.cpp, everything goes well and it produced a a.out. But, when I run g++ main1.cpp utils.cpp, this comes out:

/usr/bin/ld: /tmp/ccw11r0D.o: in function `main':
main1.cpp:(.text+0x91): undefined reference to `void vector_remove<int>(std::vector<int, std::allocator<int> >&, int const&)'
collect2: error: ld returned 1 exit status

What is the problem here?

Bi Ao
  • 486
  • 3
  • 8

0 Answers0