0

I'm making a basic C++ setup. There is a main file, which calls a function, quickSort from another file, qSort.h/qSort.cpp. However, when I try to do so I get unresolved external symbol, which means that the function prototype is visible, but not the function definition itself. However, when I move the quickSort function into the header, then it runs just fine, so it must be a problem recognizing the function definition.

The qSort header looks like:

#ifndef __qSort_h__
#define __qSort_h__

int quickSort(int * inputArray);

#endif

The qSort source looks like(empty for now as I fix this):

#include "qSort.h"

int quickSort(int * inputArray){


return 4;
}

And it is called simply in my main file as:

std::cout << quickSort(arrayInput);

and included in the main source file with:

#include "qSort.h"
#include "SortingPractice.h"
#define ARRAY_LENGTH 20

I've been told that placing any actual code in your header is terrible, so I'm looking for some advice how to do avoid doing so while getting this code to run. Thank you.

WarSame
  • 870
  • 1
  • 10
  • 24

1 Answers1

0

The compiler/linker need to know about all the parts of your program. One simple way to do this is to compile both source files together, gcc main.cpp qsort.cpp, so that it will pass both generated object files to the linker.

Or if compiling separately, you need to pass both object files to the linker.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • Unfortunately this is in Visual Studio so I don't think I can compile them together. What do you mean by passing both object files to the linker? – WarSame Oct 23 '15 at 03:49
  • `cl main.cpp qsort.cpp` then. If you're using the IDE you should have both source files listed in your project and VC should combine them. What symbol is listed in the unresolved external symbol error? – 1201ProgramAlarm Oct 23 '15 at 03:53
  • I don't understand how to use those commands within VS itself. Do you just want me to run it from CL on the files? And aren't you only supposed to include the headers, which will include the function definitions? The error message is: unresolved external symbol "class std::vector > __cdecl quickSort(class std::vector >)" and then some a bunch of other stuff in the same vein. I've changed the int[] to std::vector for my code, which is why the error says that. – WarSame Oct 23 '15 at 23:53
  • @WarSame Do you ave main.cpp and qsort.cpp both in the same project in VS? Does the prototype of quickSort in qsort.h match exactly the function definition in qsort.cpp? – 1201ProgramAlarm Oct 24 '15 at 03:13
  • The prototype matched, but I just realized what the problem was - I had added the files using New->File, which meant they simply weren't included in the project. I then included the files into the project, and it works just fine. Your original comment was right, so I am accepting it as the answer. Thanks for the help! – WarSame Oct 24 '15 at 21:06