Trouble Making a Library

Hi,

I'm fairly new to C++ and I have made my own sort algorithm. It is an insertion sort algorithm, that sorts between values being entered. I am trying to make a library with a header file "sort.h". So far, the only way I have been able to get this working is by putting the function in the header file, which I have read in other places is bad practice. Why is this?

If someone could help me to fix this up, please do. The source code of my currently working "sort.h" is below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#ifndef SORT_H
#define SORT_H
void sortInsertion(int* pnArray, int nArrSize, int nCurrentIndex)
{
     bool bQuitLoop;
     int nVal = pnArray[nCurrentIndex];
     for (int t = 0; t < nCurrentIndex; t++)
     {
         bQuitLoop = false;
         if (nVal < pnArray[t])
         {
             bQuitLoop = true;
             for (int j = nCurrentIndex; j > t; j--) 
             {
                 pnArray[j] = pnArray[j-1];
             }
             pnArray[t] = nVal;
         }
         else
         {
             pnArray[nCurrentIndex] = nVal;
         }
        
         if (bQuitLoop == true) break;
     }
}
#endif 

The actual function works, the problem I'm having is that I don't know how to do all the linking stuff. I want it to work like <math.h>, so you can just type the function call in and it works - without classes.

BTW, I'm using Dev-C++, but just source code (.cpp), no projects
hi,i guess one thing you can try is to make another .cpp file and include it in your header,like that:
for example:

your header:

1
2
3
4
5
6
7
8
9
//sort.h
#ifndef SORT_H
#define SORT_H

#include "sort.cpp"
void sortinsertion (int,int,int);

#endif



the sort.cpp file:
1
2
3
4
5
6
//sort.cpp

void sortinsertion (int pn array,int nArrSize,int nCurrentIndex )
{
  //your algorithm 
}


then you include sort.h in your main.cpp or whatever main file.

let me know if you think that's dumb,that's the way most directx tutorials do it...

Tried that just then, got an error:

[Linker error] undefined reference to `sortInsertion(int*, int, int)'

Using the old way, when I compile "sort.cpp", I got this error:

[Linker error] undefined reference to `WinMain@16'

Hope that helps
Topic archived. No new replies allowed.