coson coson - 2 months ago 6
C++ Question

Use g++ or CC to compile multiple C++ files

Good Day,

I have tried to lookup how to compile several C++ files on a *nix command line.

I've tried these two links
Using G++ to compile multiple .cpp and .h files

Using G++ to compile multiple .cpp and .h files

I have a simple abstract class:

// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;

void setWidth(int w) {
width = w;
}

void setHeight(int h) {
height = h;
}

protected:
int width;
int height;
};


Then a derived one:

// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};


Here is the driver:

#include <iostream>

using namespace std;

int main(void)
{
Rectangle Rect;

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;

return 0;
}


This is a simple one, so I don't need a makefile, but this is what I've tried:

> g++ Shape.cc - This creates a Shape.o
> g++ Shape.cc Rectangle.cc ShapeDriver.cc - This creates an error
> g++ ShapeDriver.cc Shape.cc Rectangle.ccc - This creates an error


It turns out that Rectangle.cc is not recognizing the width and height definitions, which makes sense.

What else do I need to do to get this to compile? I'm a total C++ noob.

TIA,

coson

Answer

You need to add the following to the different files...

Top of Rectangle.cc

#include "Shape.cc"

Top of ShapeDriver.cc

#include "Rectangle.cc"

Also, in your third gcc line, you have a typo

g++ ShapeDriver.cc Shape.cc Rectangle.ccc - This creates an error

It should have been Rectangle.cc

What your problem is, is that in each of your files, the different classes have never been defined, so they don't know how to use them. Like.... "Rectangle" first needs to know what a "Shape" is before it derives from it. You should be using .h files in between w/ the class definitions, and including them in the other .cc files so they know the other class structures they are calling on.

Comments