関数呼び出し(別ファイルから)

別ファイルに関数内容を記入し、コンパイル時にメインプログラムファイルとリンクさせる例です。

 手順としては、

  1. 関数内容をヘッダ、メインファイルにそれぞれ記入
  2. 関数用のファイルをコンパイルしオブジェクトファイル(*.o)を作成する。
  3. メインプログラムとオブジェクトファイルのリンク
となります。上記の説明だけでは分かりづらいと思いますので、実際にプログラムと実行結果をご覧下さい。

関数呼び出し(別ファイルから)list_45.c,swap.c,swap.h)
/* list_45.c */

#include <stdio.h>
#include "swap.h"

int main()
{
    int a, b;
    printf("第一数と第二数を交換します。\n");
    printf("第一数:");scanf("%d",&a);
    printf("第二数:");scanf("%d",&b);
    swap(&a,&b);
    printf("**********\n第一数:%d\n第二数:%d\n",a,b);
    return(0);
}


/* swap.c */ #include <stdio.h> #include "swap.h" void swap(int *a,int *b) { int temp = *a; *a = *b; *b = temp; }
/* swap.h */ #ifndef __INCLUDE_SWAP_H__ #define __INCLUDE_SWAP_H__ //----------------------------------------------------------------- // 関数宣言 //----------------------------------------------------------------- void swap(int *a,int *b); #endif //__INCLUDE_SWAP_H__
実行結果
**コンパイル&実行の流れ

Gami[231]% ls
list_45.c  list_45.h  swap.c  swap.h
Gami[232]% gcc -c swap.c
           → オブジェクトファイル(swap.o)の作成
Gami[233]% ls
list_45.c  list_45.h  swap.c  swap.h  swap.o
Gami[234]% gcc -o list_45 list_45.c swap.o
           → 作成されたオブジェクトファイルとメインプログラムとのリンク
Gami[235]% ls
list_45.c  list_45.exe*  list_45.h  swap.c  swap.h  swap.o
Gami[236]% list_45.exe
第一数と第二数を交換します。
第一数:5
第二数:8
**********
第一数:8
第二数:5
Gami[237]%
      
inserted by FC2 system