-2

When I try to compile my implementation file using g++ -c Sorting_Functions.cpp, I get this message

error: use of undeclared identifier 'IntSort'

IntSort.h

#ifndef INTSORT_H_

#define INTSORT_H_

#include "Sorting_Functions.cpp"

class IntSort 
{

public:

    IntSort();
    void print();


private:

    int arr[5];
    int len;
};

#endif

Sorting_Functions.cpp

#include "IntSort.h"

using namespace std;

IntSort::IntSort()
{

    arr[0] = 7;

    arr[1] = 3;

    arr[2] = 2;

    arr[3] = 6;

    arr[4] = 4;

    len = 5;
}

// prints the lists to the user

void IntSort::print()
{

    cout << "{ ";

    for (int i = 0; i < len; i++) {
        cout << arr[i] << " ";
    }

    cout << "}";
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 8
    Don’t include `.cpp` files: `#include "Sorting_Functions.cpp"` doesn’t work. – Konrad Rudolph Aug 12 '21 at 22:15
  • 1
    Because of above, you wound up with a circular dependency. IntSort.h needs Sorting_Functions.cpp and Sorting_Functions.cpp needs IntSort.h, but since IntSort.h has already been included the include guard prevents it from being included again. This leaves Sorting_Functions.cpp stuck because `class IntSort` hasn't been defined yet. – user4581301 Aug 12 '21 at 22:18
  • And because of the recursive inclusion (and the fact the `#ifdef` skip the file on the second loop), you will end up that the compiler will see `IntSort::IntSort()` before it see `class IntSort...` – Phil1970 Aug 12 '21 at 22:22
  • Here's a good answer that shows exactly what happens when the compiler (preprocessor, really) starts trying to interpret the files: https://stackoverflow.com/a/628079/4581301 – user4581301 Aug 12 '21 at 22:24

1 Answers1

1

The problem is the inclusion of a source file (.cpp or .cc). Only header files (.h) should be included, and all source files should be compiled. Remove the source file #include and the code should be fine.

The "undeclared identifier" error is caused by Sorting_Functions.cpp including IntSort.h which in turn includes Sorting_Functions.cpp - the compiler will first see the type IntSort being used, which at this point has not yet been declared (which happens in IntSort.h after the #include).

Yun
  • 3,056
  • 6
  • 9
  • 28
  • Note: Once the .cpp file is no longer included, you may have to tell your build tools to compile and link it. Many build tools are smart enough to recognize a cpp file and automatically compile and link it, and this is where you usually get in trouble: everything in the cpp file winds up multiply defined. It's in the cpp file and also in every file that included the cpp file. – user4581301 Aug 12 '21 at 22:36