gpt4 book ai didi

c++ - 对 `void sort::swap(int*, int, int)' 的 undefined reference

转载 作者:行者123 更新时间:2023-11-28 08:20:27 28 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Why can templates only be implemented in the header file?

这是我的制作文件:


#!/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


这是我的 C++ 文件:


// 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;
}

还有,这是我的问题:

./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

知道如何解决这个问题吗?

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com