1

I've been following tutorial on how to create class using header files and came to a problem even if I did everything like in tutorial. I got Cat.h, Cat.cpp and main.cpp files. All of them are in the same folder.

Cat.h:

#ifndef CAT_H_
#define CAT_H_

class Cat
{
public:
    void speak();
};

#endif

Cat.cpp:

#include <iostream>
#include "Cat.h"

using namespace std;

void Cat::speak()
{
    cout << "Meeeow!" << endl;
}

main.cpp:

#include <iostream>
#include "Cat.h"

using namespace std;

int main()
{
   Cat jim;
   jim.speak();

   return 0;
}

When i run the program I got error: "undefined reference to `Cat::speak()'". The problem is solved when i add line #include "Cat.cpp" to main.cpp but I dont think thats a way to go and tutorial was done without that.

softcactus
  • 31
  • 2
  • How are you compiling your code? – Nathan Pierson Jul 03 '21 at 02:08
  • Without knowing what build toolchain you use, only appropriate answer is: https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix – Swift - Friday Pie Jul 03 '21 at 02:11
  • 1
    Your description sounds like you are not compiling and linking Cat.cpp. – user4581301 Jul 03 '21 at 02:12
  • 1
    Im running code in VS Code along with MinGW compiler installed. I run the code using Code Runner extension (which i think manually compiles the code?) How do I compile and link Cat.cpp? I'm newbie to those stuff. – softcactus Jul 03 '21 at 02:18
  • 1
    You need to modify your tasks.json to get it to build all of your sources. The documentation explains the default setting is to build only the active file and how to make the change to build all cpp files in the workspace folder: [https://code.visualstudio.com/docs/cpp/config-mingw#_modifying-tasksjson](https://code.visualstudio.com/docs/cpp/config-mingw#_modifying-tasksjson) – drescherjm Jul 03 '21 at 02:21
  • Found the solution in different thread. Because Im using Code Runner extension I had to edit line in settings.json to include whole folder instead just one .cpp file. Thanks for explaning what my problem was – softcactus Jul 03 '21 at 02:46

1 Answers1

0

Solved. For anyone having the same problem using VS Code with Code Runner extension, I found the solution in different thread: Code-runner configuration for running multiple cpp classes in vscode

softcactus
  • 31
  • 2
  • My comment above was a bit too slow. You don't want to make an answer that is effectively link to an existing question. Prefer to close the question as a duplicate of the the other question. – user4581301 Jul 03 '21 at 02:51