가능한 중복 :정의되지 않은 참조
:#!/usr/bin/make -f compiler = g++ compiler_flags = -Wall -I /usr/include/c++/4.5 debug_flags = -D DEBUG -g binary_filename = sort_testing.bin all: clean release release: $(compiler) $(compiler_flags) main.cpp sort.o -o $(binary_filename) debug: sort.o $(compiler) $(debug_flags) $(compiler_flags) main.cpp sort.o -o $(binary_filename) run: ./$(binary_filename) clean: rm -f *.o $(binary_filename) sort.o: $(compiler) $(debug_flags) $(compiler_flags) -c sort.cpp
Why can templates only be implemented in the header file?
여기에 내 메이크 파일의
./make clean debug
rm -f *.o sort_testing.bin
g++ -D DEBUG -g -Wall -I /usr/include/c++/4.5 -c sort.cpp
g++ -D DEBUG -g -Wall -I /usr/include/c++/4.5 main.cpp sort.o -o sort_testing.bin
/tmp/ccRl2ZvH.o: In function `main':
/home/dev/c++/sorting/main.cpp:33: undefined reference to `void sort::swap<int>;(int*, int, int)'
collect2: ld returned 1 exit status
make: *** [debug] Error 1
어떤 생각이 문제를 해결하는 방법 : 여기 내 문제입니다,
// sort.hpp
#ifndef SORT_H
#define SORT_H
namespace sort{
template<class T> void swap(T*,int,int);
}
#endif
// sort.cpp
#include "sort.hpp"
namespace sort{
template<class T>
void swap(T* items, int index_a, int index_b){
T t = items[index_a];
items[index_a] = items[index_b];
items[index_b] = t;
}
}
// main.cpp
#include <iostream>
#include <exception>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
#include "sort.hpp"
using namespace sort;
#define NUM_INTS 5
int main(int argc, char** argv){
try{
cout << "\n\n\n";
srand(time(NULL));
int * int_coll = new int[NUM_INTS];
for (int x = 0; x < NUM_INTS; x++)
int_coll[x] = rand() % 100 + 1;
cout << "Before swap" << endl;
for (int x = 0; x < NUM_INTS; x++)
cout << "int " << x << " == " << int_coll[x] << endl;
cout << "\n\n\n";
cout << "Swapping ints" << endl;
swap<int>(int_coll, 0, 1);
cout << "AFter swap" << endl;
for (int x = 0; x < NUM_INTS; x++)
cout << "int " << x << " == " << int_coll[x] << endl;
}catch(exception& e){
cout << "Exception: " << e.what() << endl;
}
return 0;
}
그리고 :
여기 내 C + +를 파일입니까?
'swap'이 필요하지 않습니다. 타입은'int_coll'에서 추론 할 수 있습니다. –
Xeo