C++ compile multiple cpp and header files via -I. cpp1.cpp cpp2.cpp -o

1.The first header file.

//DynamicArray.h
#include <cassert> #include <stdio.h> #include <stdlib.h> using namespace std; class DynamicArray { private: int _size; int _max; int *_arrayHolder; public: DynamicArray(); ~DynamicArray(); int size(); int &operator[](int i); void add(int n); void printArray(); };

2.The first source file

//DynamicArray.cpp
#include <DynamicArray.h> DynamicArray::DynamicArray() { this->_size=0; this->_max=5; this->_arrayHolder=new int[5]; } DynamicArray::~DynamicArray() { delete[] this->_arrayHolder; } int DynamicArray::size() { return this->_size; } int& DynamicArray:: operator[](int i) { assert(i<this->_size); return this->_arrayHolder[i]; } void DynamicArray:: add(int n) { if(this->_max<this->_size+1) { this->_max*=2; int *tmp=new int[this->_max]; for(size_t i=0;i<this->_size;i++) { tmp[i]=this->_arrayHolder[i]; } delete[] this->_arrayHolder; this->_arrayHolder=tmp; this->_arrayHolder[this->_size]=n*n*n*n; this->_size+=1; } else { this->_arrayHolder[this->_size]=n*n*n*n; this->_size+=1; } } void DynamicArray:: printArray() { for(int i=0;i<_size;i++) { printf("Index=%d,value=%d in printArray()\n",i,_arrayHolder[i]); } }

3.The second header file

//MathHelper.h
#include <iostream> #include <math.h> using namespace std; class MathHelper { public: int getDouble(int x); int getTriple(int x); int getSquare(int x); int getCube(int x); };

4.The second source file

//MathHelper.cpp

#include <MathHelper.h>

int MathHelper::getDouble(int x)
{
    return x*2;
}

int MathHelper::getTriple(int x)
{
    return x*3;
}

int MathHelper::getSquare(int x)
{
    return x*x;
}

int MathHelper::getCube(int x)
{
    return x*x*x;
}

 

5.The key step is to add header files in main  cpp file as below

#include <DynamicArray.h>
#include <MathHelper.h>

6.The main.cpp as below

#include <iostream>
#include <uuid/uuid.h>
#include <vector>
#include <DynamicArray.h>
#include <MathHelper.h>

using namespace std;

void dynamicArr4();
void math5();


int main()
{
    dynamicArr4();
    math5();
    return 0;
}

void math5()
{
    MathHelper mh;

    for(int i=0;i<1000;i++)
    {
        cout<<"Index="<<i<<",value="<<mh.getCube(i)<<endl;
    }
    printf("In math5() method!\n");
}

void dynamicArr4()
{
    DynamicArray dArray;
    vector<int> vArray;

    for(size_t i=0;i<=100;i++)
    {
        dArray.add(i);
    }
    dArray.printArray();
}

 

6.Caution. Pay more attentio to the -I.   which will include the current directory

When you begin to compile the main cpp file via gcc,it will and the '-I.' (i 'me' uppercase) to include the current directory files as below.

g++ -g -std=c++2a -I. DynamicArray.cpp MathHelper.cpp h1.cpp -o h11 -luuid

7.The compiled result as below 

 

 8.Run the compiled output

./h11

 

posted @ 2021-12-04 13:31  FredGrit  阅读(54)  评论(0编辑  收藏  举报