1

I am a complete beginner to c++. I am learning c++ through the object oriented programming Data structures in c++. In the course I have the following program

Cube.h

#pragma once

class Cube {
  public:
    double getVolume();
    double getSurfaceArea();
    void setLength(double length);

  private:
    double length_;
};

Cube.cpp

#include "Cube.h"

double Cube::getVolume() {
  return length_ * length_ * length_;
}

double Cube::getSurfaceArea() {
  return 6 * length_ * length_;
}

void Cube::setLength(double length) {
  length_ = length;
}

main.cpp

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

int main() {
  Cube c;

  c.setLength(3.48);
  double volume = c.getVolume();

  std::cout << "Volume" << volume << std::endl;

  return 0;
}

When I make this program with make main, I get the following error message

c++     main.cpp   -o main
Undefined symbols for architecture x86_64:
  "Cube::getVolume()", referenced from:
      _main in main-6c5fe0.o
  "Cube::setLength(double)", referenced from:
      _main in main-6c5fe0.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [main] Error 1

Not sure what I am doing wrong. I am working from a macbook. I followed this link to run cpp programs in mac.

Not sure what I am doing wrong. An explanation to the error will also be nice.

Thanks in advance

Sashaank
  • 880
  • 2
  • 20
  • 54
  • 3
    Hello, you should complie also the Cube.cpp, like c++ *.cpp -o main. – g_bor Sep 15 '20 at 14:29
  • 1
    its an interesting zoo of answers on [this question](https://stackoverflow.com/questions/221185/how-to-compile-and-run-c-c-in-a-unix-console-mac-terminal). for some reason all assume that you compile a single source file and don't apply in your case – 463035818_is_not_an_ai Sep 15 '20 at 14:30
  • @idclev463035818 sorry for the ignorance. As I explained in the question, I am complete beginner and do not yet understand the errors. Have learnt this now – Sashaank Sep 15 '20 at 14:33
  • @Sashaank no need to be sorry. Maybe the authors of the answers should be ;) – 463035818_is_not_an_ai Sep 15 '20 at 14:34

1 Answers1

3

You need to link main.cpp and Cube.cpp together, so you have to compile with:

c++ main.cpp Cube.cpp -o main
Aplet123
  • 33,825
  • 1
  • 29
  • 55