0

I am new to C++ (like super new) and I'm learning how to create classes in header files and calling them in the main function. I created a header file with the class and a cpp file that contains the functions.

The class I am creating is a dog. The dog barks when the void function "speak" is called.

Here is my main function.

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

using namespace std;

int main(){

    Dog dog;

    dog.speak();

    return 0;
}

Here is the cpp file that contains the function.

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

using namespace std;

void Dog::speak(){

    cout << "bark" << endl;

}

Here is the header file with the class.

#ifndef DOG_H_
#define DOG_H_

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

#endif /* DOG_H_ */

The error I'm getting when trying to build the file with the void function is:

C:\temp\gcc\build-mingw-w64\mingw-w64-crt/../../src/mingw-w64-crt/crt/crt0_c.c:18: undefined reference to `WinMain

This is the error I get when trying to build the code with the main function:

C:/mydirectory/datamembers.cpp:10: undefined reference
to `Dog::speak
()'

When I try to run the code in the main function, I get this error:

undefined reference to `Dog::speak()'
collect2.exe: error: ld returned 1 exit status

I am using the latest version of Visual Studio. I read that Visual Studio is trying to run the code as GUI when it should be trying to run it as command line. All the files are in the same source file. Is there a setting that I need to change to make the code work?

  • are you using visual studio or mingw? Do you perhaps mean visual studio code? You need to compile your source files into object files rather than executables then link both objects into an executable – Alan Birtles Oct 24 '21 at 19:02

0 Answers0