リスト1〜4が分割コンパイルの例である.このプロ
グラムは,関数
を指定された数で
を分割し,値をファイル
に書き出す.最初の2つのプログラムに,アルゴリズムは次のようになっていることがわ
かる.
これまでとはことなり,この動作のプログラムは以下に示す4つのファイルからできている.
| main.c | プログラムのメイン関数を書いている.プログラム全体を統括する役割が ある.メイン関数を見れば,プログラム全体の流れが分かる. |
| functions.c | さまざまな関数の記述がある.ここでは,目的の処理を行うために,関数単位で機能を提供する. |
| functions.h | 関数の集まりである functions.c のプロトタイプ宣言をまとめて いる. |
| Makefile | 分割ファイルから,実行ファイルを作る手順が書いてある. |
これらのファイルの役割や書き方については,次の節で詳しく説明する.
1 #include <stdio.h>
2 #include "functions.h"
3
4 int main(void)
5 {
6 int n;
7
8 n=input_data();
9 make_data(n);
10
11 return 0;
12 }
1 #include <stdio.h>
2 #include <math.h>
3 #include "functions.h"
4
5 //=======================================
6 // データ数の取得の関数
7 //=======================================
8 int input_data(void)
9 {
10 int num;
11
12 printf("How many datas?\t");
13 scanf("%d",&num);
14
15 return num;
16 }
17
18 //=======================================
19 // ファイルの作成
20 //=======================================
21 int make_data(int nd)
22 {
23 int i;
24 double dx, x;
25 FILE *out;
26
27 out=fopen("result.dat", "w");
28
29 dx = 2*M_PI/nd;
30 for(i=0; i<=nd; i++){
31 x=i*dx;
32 fprintf(out,"%f\t%f\n", x, f(x));
33 }
34
35 fclose(out);
36
37 return 0;
38 }
39
40 //=======================================
41 // 数学関数
42 //=======================================
43 double f(double x)
44 {
45 return x+x*sin(x);
46 }
1 int input_data(void); 2 int make_data(int nd); 3 double f(double x);
1 mkdat : main.o functions.o 2 gcc -o mkdat main.o functions.o -lm 3 4 main.o : main.c 5 gcc -c main.c 6 7 function.o : function.c 8 gcc -c function.c