文件分割,make及makefile的使用

1.文件分割:

     Linux c文件分割,主要是把每个自定义函数分割成独立的c源程序文件,自定义函数的声明部分需要包含在主调函数中,这儿的主调函数是main。如果自定义函数较多,也可以把函数声明都分割成独立的头文件,在主调函数中用#include包含分割出来的头文件。

   举例:

   求平均数的实例:

   讲程序分成两个.cpp文件,一个.h文件。分别为test-main.cpp, test-Average.cpp, test-Average.h

   test-main.cpp的内容:

  

#include<iostream>
#include "test-Average.h"
using namespace std;
int main()
{
  int n;
  float average;
  cout << "How many numbers do you want to input?";
  cin >> n;
  int a[n];
  for(int i=0; i<n; i++)
  {
     cout << "输入第" << i+1 << "个数字为:";
     cin >> a[i];
  }
  average = Average(n, a);
  cout  << "平均值为" << average << endl;
}

     test-Average.cpp的内容:

float Average(int n, int a[])
{
  float average = 0.0;
  for(int i=0; i<n; i++)
    average += a[i];
  average /=n;
  return average;
}

  test-Average.h的内容:

float Average(int n, int a[]);
  编译运行以上程序:

   g++  test-main.cpp  test-Average.cpp -o test

   ./test


2.make的使用及makefile的编写

实例:有三个源文件score.cpp, Sum.cpp, Average.cpp及一个头文件score.h

score.cpp中内容:

#include <iostream>
#include "score.h"
using namespace std;
int main()
{
  float sum, average;
  float score[5] = {91, 98, 100, 89, 79};
  sum = Sum(score, 5);
  average = Average(score, 5);
  cout << "The sum score is " << sum << endl;
  cout << "The average score is " << average << endl;
  return 0;
}

Sum.cpp中内容:

float Sum(float var[], int num)
{
    float sum = 0;
    for(int i=0; i<num; i++)
        sum += var[i];
    return sum;
}

Average.cpp中内容:

float Average(float var[], int num)
{
    float average = 0;
    for(int i=0; i<num; i++)
        average += var[i];
    average /= num;
    return average;
}

score.h中内容:

float Sum(float var[], int num);
float Average(float var[], int num);

makefile文件的编写:

在该项目中,makefile文件的名字取为makefile_score,内容如下:

score: score.o Sum.o Average.o
    g++ score.o Sum.o Average.o -o score
score.o: score.cpp score.h
    g++ score.cpp score.h -c
Sum.o: Sum.cpp
    g++ Sum.cpp -c
Average.o: Average.cpp
    g++ Average.cpp -c

make的使用:

make -f makefile_score


通过以上步骤,就生成了最终的可执行文件score了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值