coson coson - 1 year ago 96
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
// pure virtual function providing interface framework.
virtual int getArea() = 0;

void setWidth(int w) {
width = w;

void setHeight(int h) {
height = h;

int width;
int height;

Then a derived one:

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

Here is the driver:

#include <iostream>

using namespace std;

int main(void)
Rectangle Rect;


// 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++ - This creates a Shape.o
> g++ - This creates an error
> g++ Rectangle.ccc - This creates an error

It turns out that 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.



Answer Source

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

Top of

#include ""

Top of

#include ""

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

g++ Rectangle.ccc - This creates an error

It should have been

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download