0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Cの基本8 〜ソースファイル・分割コンパイル〜 備忘録

Last updated at Posted at 2023-02-17

はじめに

私は初心者である。この備忘録を参考にされようとしている他の初心者の方は、ここに書かれていることを鵜呑みになさらぬようお願いしたい。何か間違いを見つけた方はコメント欄でご報告頂きたい。

このまとめは理解がしきれてない段階で書いたから分かりづらいかも。後の「分割コンパイルを使いこなしたい」も参考に。


コンパイルとリンク (分割コンパイル)

これまではソースファイルを一つ作り、それをコンパイルして実行可能ファイルを作成してきた。この実行可能ファイルの作成には、ソースファイルから機械語のオブジェクトファイルを生成する過程(コンパイル)と生成されたオブジェクトファイルとライブラリにあるオブジェクトファイルを結合して実行可能ファイルを作る過程(リンク)がある。

今までのような一つのソースファイルから実行可能ファイルを作成するやり方とは別に分割コンパイルというものがある。
複数のソースファイルをコンパイルし、できたオブジェクトファイルを結合して一つの実行可能ファイルを作るやり方だ。

フィボナッチ数列のプログラムを2つのソースファイルに分けて作成した例が以下

main.c
#include <stdio.h>
#include "fibsub.c"    

int fib(int);

int main(void){
    for(int i = 1; i < 10; i++)
    printf("fib(%d) = %d\n", i, fib(i));
    // return 0;
}
fibsub.c
int fib(int);

int fib(int n) {
    if(n==1 || n==2)
        return 1;
    else
        return fib(n-2) + fib(n-1);
    
}

main.cの中でint fib(int);も関数宣言している。変数だけではなく関数も他ファイルにある場合でも宣言するべきなのだろう。

下記は入力された金額から税込価格を表示するプログラムだ

main.c
#include "tax.c"

extern double rate;

int tax(int);

int main(void){
    int price, pay;

    rate = 8.0;
    printf("price? ");
    scanf("%d", &price);
    pay = price + tax(price);
    printf("You pay %d\n", pay);
    return 0;
}
tax.c
double rate;

int tax(int);

int tax(int price){
    return price*rate / 100.0;
}

main.cにあるextern double rate;int tax(int);は無くても動いたが、エラーをなくすためには書くべきだ。

書籍にある記述をメモっとく

  • 定義はソースプログラム全体の中のどこか一箇所で行う
  • 宣言はそれを使うコードがあるソースファイルの、使っている場所より上に置く

関数や外部変数の宣言は、余分にあっても害はほとんどないらしい。だから宣言漏れの防止のために、全ての宣言を全てのファイルに入れることもあるそうだ。


今回の内容は富永和人氏の新しいC言語の教科書を参考に書き留めてます。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?