#include と #define がよく使われる。
#include <stdio.h>
では、stdio.h というファイルを読み込むことで printf などの関数が利用可能になっている。
実際に stdio.h というファイルは用意されているのか?
→実際にファイルとして用意されている。
Microsoft Visual Studio 2005 Express Edition の場合、「C:\Program Files\Microsoft Visual Studio 8\VC\include」に stdio.h というファイルがある。
また、自作の関数も別ファイルから読み込み可能。
ヘッダーファイルも同じディレクトリにある場合には「"myhead.h"」のように「"」でくくる
→ソースコードファイルの分割が可能
hellomyheader.h
int myfunc(int a, int b){
return a * 2 + b;
}
hellomyheader.c
#include <stdio.h>
#include "hellomyheader.h"
int main(void){
int a=2,b=3,c;
c = myfunc(a,b);
printf("%d\n",c);
}
#define を使って、指定した文字列を置き換えることもできる。
以下の例では MESSAGE という文字列が "hello" に置き換えられる。
hellodefine1.c
#include <stdio.h>
#define MESSAGE "hello"
int main(void){
printf("%s\n",MESSAGE);
}
hellodefine1b.c
#include <stdio.h>
int main(void){
printf("%s\n", "hello");
}
hellodefine1.c は hellodefine1b.c と実質的に同じプログラムである。
また #define にはパラメータを渡すことも可能である。
hellodefine2.c
#include <stdio.h>
#define add(a,b) ((a)+(b))
int main(void){
printf("%d\n",add(2,3));
}
hellodefine2b.c
#include <stdio.h>
int main(void){
printf("%d\n",((2)+(3)));
}
演習
本資料サンプル
hellomyheader.h + hellomyheader.c
hellodefine1.c
hellodefine2.c
教科書257ページ練習問題1
メールで提出
cl.exe の場合 /EP というオプションを付けることで、前処理のみを行った場合の結果を確認することもできる
helloprep.c
#define DEBUG 1
int main(void){
if(DEBUG){ /* 処理1 */ }
else{ /* 処理2 */ }
}
>cl /EP helloprep.c
int main(void){
if(1){ }
else{ }
}