0

I'm new to cpp and learning oop. While working with headers and classes, I'm trying to define the function speak() in one file {Cat.cpp} and use headers {Classes.cpp} to use it in another file. {Cat.h}. I've did all the coding right but still error message pops up.

C:\Users\DELL\AppData\Local\Temp\cc0QWD1m.o:Classes.cpp:(.text+0xc): undefined reference to `speak()' collect2.exe: error: ld returned 1 exit status

These are the respective files:-

Cat.cpp

#include <iostream>

#include "Cat.h"

using namespace std;
void speak() {

    cout << "Sound" << endl;
   


}

Classes.cpp

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

using namespace std;

int main()
{

    speak();
    return 0;
}

Cat.h

#ifndef CAT_H_
#define CAT_H_

void speak();


#endif 

The tutorial guy seems to do the same thing and gets it write, does it have something to do with the IDE, he is using eclipse.

I'm Using - VSCode as IDE & G++ Compiler.

Where am I going wrong?

drescherjm
  • 10,365
  • 5
  • 44
  • 64
Merlin
  • 1
  • 4
  • 1
    This happens if you try to build a single file separately, instead of having a project combining all .cpp files needed by your program. – Ben Voigt Aug 24 '21 at 18:46
  • How did you add `Cat.cpp` to the project? Does Visual Studio Code know that it needs to compile Cat.cpp? – user4581301 Aug 24 '21 at 18:47
  • Your question is covered by [this existing answer](https://stackoverflow.com/a/12574400/103167) – Ben Voigt Aug 24 '21 at 18:47
  • Eclipse scans the project folder and adds any .cpp files it finds to the build instructions (which can cause its own set of problems) , but I believe VSCode requires a bit more configuring. – user4581301 Aug 24 '21 at 18:50
  • ***Where am I going wrong?*** My expectation is you failed to edit your tasks.json file as the documentation tells you here: [https://code.visualstudio.com/docs/cpp/config-mingw#_modifying-tasksjson](https://code.visualstudio.com/docs/cpp/config-mingw#_modifying-tasksjson) failure to modify tasks.json makes VSCode only build the active file into your executable. – drescherjm Aug 24 '21 at 18:57
  • Thanks, in VScode I was trying to run Coderunner directly only on Classes.cpp thus all the files weren't compiling & wasn't mentioning files while compiling in g++ aswell. Once I mentioned both files in g++ by doing -> g++ -o Classes Classes.cpp Cats.cpp It worked out. Thanks for all the help. – Merlin Aug 24 '21 at 19:32

0 Answers0