When I begin to learn C++ and algorithms. I want to group code in module paradigm. so I had divide the sort procedure into 3 files, as follows:
sort.h
namespace sort
{
void insertSort(int* a,int size);
}
sort.cpp
#include "sort.h"
namespace sort
{
}
void sort::insertSort(int* a,int size)
{
int i,j,key;
for(j=1;j<size;j++)
{
key=a[j];
i=j-1;
while(i>=0 && a[i]>key)
{
a[i+1]=a[i];
i=i-1;
}
a[i+1]=key;
}
}
main.cpp
#include<iostream>
#include"sort.h"
int main()
{
int a[6]={5,2,4,6,1,3};
sort::insertSort(a,6);
for(int i=0;i<6;i++) std::cout<<a[i]<<'\t';
return 0;
}
When I use Dev-C++ to compile the three files. I got the the below error information:
[Linker Error] undefined reference to `sort::insertSort(int*, int)’
I don’t know why. I think I have include the file “sort.h”, so why is it also telling me that the compile can’t reference to the method sort::insertSort()?
When you’re building the entire program, make sure you’re linking all the object files together. The linker is complaining because your
main()function is calling thesort::insertSortfunction, which has been declared insort.h, but the definition for which has not been included in the program as a whole.I don’t know offhand what parameters to your particular Dev-C++ environment are required, but typically, make sure that all the
cppfiles are in the command line you send to the compiler frontend.