I have a simple function declared in header file and defined cpp file. When I delete the test_vector
function in cpp file, I got this error.
Undefined symbols for architecture x86_64:
"void chapter3::print_vector<int>(std::__1::vector<int, std::__1::allocator<int> > const&)",
referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
What's going on here?
// chapter3.hpp
#ifndef chapter3_hpp
#define chapter3_hpp
#include <stdio.h>
#include <vector>
namespace chapter3 {
template<typename T>
void print_vector(const std::vector<T>&);
}
#endif /* chapter3_hpp */
// chapter3.cpp
#include "chapter3.hpp"
#include <iostream>
#include <vector>
using namespace std;
namespace chapter3 {
template<typename T>
void print_vector(const vector<T>& vec) {
for(auto& elem: vec) {
cout << elem << ' ';
}
cout << endl;
}
void test_vector() {
vector<int> u(10, -1);
print_vector(u);
}
}
// main.cpp
#include <iostream>
#include <vector>
#include "chapter3.hpp"
using namespace std;
int main(int argc, const char * argv[]) {
vector<int> vec {1,2,3};
chapter3::print_vector(vec);
return 0;
}