0

I am new to C++ and I am creating a very simple program using classes. I am using Visual Studio Code to write my code and MinGW compiler to build and run it. I have written the following code as an example to show my problem.

Main.cpp

#include "class.h"

using namespace std;

int main(void) {
    myClass myObject;
    myObject.sum(10, 20);
    return 0;
}

class.h

#pragma once

class myClass{
    public:
        void sum(int a, int b);
};

class.cpp

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

using namespace std;

void myClass::sum(int a, int b) {
    cout << "The sum = " << a + b << endl;
}

The compiler is giving me this error when I try to build it.

undefined reference to `myClass::sum(int, int)' collect2.exe: error: ld returned 1 exit status

BTW I know there are a lot of similar questions on the forum and I am sorry I am posting it again but all those solutions didn't seem to work for me as my program here is pretty simple. Any help will be very appreciated. Thanks!

Abhinava B N
  • 165
  • 1
  • 12
SumranMS
  • 3
  • 1
  • Is there a reason not to use MSBuild when developing toy project in Visual Studio? You would save yourself a lot of headache whilst just learning to code in any language. – Croolman Jan 06 '21 at 09:35
  • @Croolman poor internet, campus internet or air-gapped machine. Not everyone live, study or work somewhere they can download dozens of Gb of software for toy\experimental project. – Swift - Friday Pie Jan 06 '21 at 09:47
  • @Swift-FridayPie fair point. – Croolman Jan 06 '21 at 09:59
  • I do believe there is an issue with your build command. Can you post the command with which you build the project? – Croolman Jan 06 '21 at 10:00
  • @Croolman This is my build command ```g++ main.cpp -o main``` Pretty simple – SumranMS Jan 06 '21 at 13:25
  • And yes I did use Visual Studio before switching to VS Code but VS was pretty annoying I had to create a new project every once in a while for the same code as it would not let me build it after I have run the program a few times. Very strange – SumranMS Jan 06 '21 at 13:27
  • And theres your issue. Read some tutorial on how to build a program in gcc. You have to list all the files for the program to build. You have just listed main. – Croolman Jan 07 '21 at 05:51
  • @Croolman I got it man. Thanks for the help – SumranMS Jan 07 '21 at 07:12

0 Answers0