使用g++或CC编译多个c++文件

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

本文关键字:c++ 文件 编译 g++ CC 使用      更新时间:2023-10-16

大家好,

我试图查找如何在*nix命令行上编译几个c++文件。

我试过这两个链接使用g++编译多个。cpp和。h文件

使用g++编译多个。cpp和。h文件

我有一个简单的抽象类:
  // 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;
  };

然后是派生的

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

这是驱动程序:

  #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;
  }

这是一个简单的,所以我不需要一个makefile,但这是我尝试过的:

> 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

结果是矩形。Cc不识别宽度和高度的定义,这是有意义的。

我还需要做什么来编译这个?我对c++一窍不通。

TIA,

coson

您需要在不同的文件中添加以下内容…

矩形顶部。cc

#include "Shape.cc"

ShapeDriver.cc顶部

#include "Rectangle.cc"

同样,在第三行gcc中,有一个错别字

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

应该是Rectangle.cc

你的问题是,在你的每个文件中,不同的类从来没有被定义过,所以他们不知道如何使用它们。喜欢……"矩形"首先需要知道"形状"是什么,然后才能从它派生出来。您应该在w/类定义之间使用。h文件,并将它们包含在其他。cc文件中,以便它们知道它们正在调用的其他类结构。