0

I'm trying to use multiple files for the first time in C++. Here are the files I wrote.

File #1: Box.hpp

#ifndef BOX_HPP
#define BOX_HPP

class Box
{
    private:
        int length;
        int width;
        int height;
    
        Box() {}

    public:
        Box(int _length, int _width, int _height);

        void set_dimensions(int _length, int _width, int _height);
        int volume();
 };

 #endif

File #2: Box.cpp

#include "Box.hpp"

Box::Box(int _length, int _width, int _height)
{
    set_dimensions(_length, _width, _height);
}

void Box::set_dimensions(int _length, int _width, int _height)
{
    length = _length;
    width = _width;
    height = _height;
}

int Box::volume()
{
    return length*width*height;
}

File #3: main.cpp

#include "Box.hpp"
#include <iostream>

int main()
{
    Box box1 = Box(1,2,3);
    std::cout << box1.volume() << std::endl;
    return 0;
}

When I try to run main.cpp I get the following errors:

undefined reference to 'Box::Box(int, int, int)'

undefined reference to 'Box::volume()'

I cannot figure out why.

Community
  • 1
  • 1
Lucchini
  • 13
  • 5

1 Answers1

1

You need to compile using both files like:

$ g++ main.cpp Box.cpp  

I think You are compiling like this:

$ g++ main.cpp
Ashwani
  • 1,938
  • 11
  • 15