皆さんこんにちわ
お元気ですか?私は元気です。
さて、本日はプリプロセッサについて
#defineとか#ifdefとかがそれにあたりますね。
一番有名かつ使われてるのはおそらく#includeでしょうか。
それらを解説していきましょう。
プリプロセッサって?
ソースコードをコンパイルする前の処理をプリプロセスと呼ぶそう。
その時に動作する処理のことをプリプロセッサらしい。
#define、#if、#includeなどなどがそれに当たります。
Example
先に例を提示します。
#pragma once #include <iostream> #define N 100 #define SIZE 100 #define DOUBLE_SIZE (N+SIZE) using namespace std; int add(){ cout << "Function名:" << __FUNCTION__ << endl; cout << "Function名(引数有り):" << __PRETTY_FUNCTION__ << endl; } int diff(){ cout << "Function名:" << __FUNCTION__ << endl; cout << "Function名(引数有り):" <<__PRETTY_FUNCTION__ << endl; } int main(int argc, char const *argv[]){ #ifdef TEMP cout << "TEMPが定義されています。" << endl; #endif #ifndef TEMP cout << "TEMPが定義されていません" << endl; #endif #if (N == SIZE) cout << "Nは100です。" << endl; #endif # cout << "DOUBLE_SIZE:" << DOUBLE_SIZE << endl; cout << "File名:" << __FILE__ << endl; cout << "行数:" << __LINE__ << endl; cout << "日付:" << __DATE__ << endl; cout << "時間:" << __TIME__ << endl; cout << "N:" << N << endl; add(); diff(); return 0; }
結果
TEMPが定義されていません Nは100です。 DOUBLE_SIZE:200 File名:main.cpp 行数:32 日付:Jun 26 2014 時間:12:15:44 N:100 Function名:add Function名(引数有り):int add() Function名:diff Function名(引数有り):int diff()
プリプロセッサ
include
ヘッダーファイルの読み込み
ヘッダーとしてファイルを読み込むだけです。
#include <iostream> #include "./temp.hpp"
define
定数宣言
#define N 100 cout << N << endl; //100が出力
コンパイル時にNが100に置き換わります。
pragma
二重インクルード防止
#pragma once
ifdef,ifndef
#ifdef TEMP cout << "TEMPが定義されています。" << endl; #endif #ifndef TEMP cout << "TEMPが定義されていません" << endl; #endif
TEMPがdefineされているかどうか。
ndefのnは否定です。
if
#if (N == SIZE) cout << "Nは100です。" << endl; #endif
その条件式が合っていれば実行する。
プリプロセッサ変数
変数 | 表示 |
__FILE__ | ファイル名 |
__FUNCTION__ | 関数名 |
__PRETTY_FUNCTION__ | 関数名 |
__DATE__ | 日付 |
__TIME__ | 時間 |
__LINE__ | 行数 |
感想
使えるとデバッグにも使えるので、適宜使っていければいいと思っています。