I'm a C++ noob, so please go easy on me if my doubt seems too trivial.
#pragma once
class cube
{
public:
double getVolume();
double getSA();
void setLength(double length);
private:
double length_;
};
This is my header file cube.h ^^^
#include "cube.h"
double cube::getVolume()
{
return length_ * length_ * length_;
}
double cube::getSA()
{
return 6 * length_ * length_;
}
void cube::setLength(double length)
{
length_ = length;
}
This is cube.cpp and the next is main.cpp
#include "cube.h"
#include <iostream>
int main()
{
cube c;
c.setLength(3.48);
double vol = c.getVolume();
std::cout << "Vol: " << vol;
return 0;
}
Question 1: So when I include the implementation in .h file itself without using .cpp, the code runs as expected. But when I separate the .h and .cpp files, I get an error saying: 'undefined reference to cube::setLength(double)', 'undefined reference to
cube::getVolume()'' and 'exited with code=1 in 0.47 seconds'.
I ran it on VS Code and just set it up, and just ran a simple cin/cout and a hello world program. Is there something wrong I'm doing with the code itself or is it an error due to VS Code? Do note that this problem occurs only when I separate the .h and .cpp files.
Question 2: Why even separate the .h and .cpp files?
Edit 1: As @KamilCuk pointed out, the problem might be in linking the main.cpp and cube.cpp files, but I have no clue how you 'link' the cpp files for compilation?
Edit 2: I just might be compiling it the wrong way. I usually just click the Code Runner enabled run button on the top right, but I have no clue how to compile two files at once.