您的位置:首页 > 其它

文件分割,make及makefile的使用

2014-09-06 20:19 260 查看
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
;
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了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: