FromNandの日記

自分的備忘録

【C言語マクロ】どのファイルの何行目から呼ばれているかを調べる方法

なんだか今は規格で廃止されているかもしれないけど、どのファイルのどの行から呼ばれたかを調べてくれるマクロが紹介されている。

コンパイラが色々情報を補って実現されているものらしい。すごい。

参考 : Finding out where a function was called from - Eli Bendersky's website
 

ちなみに簡単にc言語用のプログラムに書き替えたものがこちらになる。

// In test.c

#include <stdio.h>

// Macro substitution
#define foo(a) foo_aux(a, __FILE__, __LINE__)

// Forward declaration
void foo_aux(int a, char* file, int line);

int main(){
    // Call foo(6), but actually foo_aux(6, 
    // [line number], [file name]) when the 
    // line number and file name are inserted 
    // by the compiler
    foo(6);
    return 0;
}

// Same function as "foo", just changed
// the name
void foo_aux(int a, char* file, int line){
    printf("function foo_aux is called from %s and line is %d\n", file, line);
    return;
}


実行結果は次のようになる。

function foo_aux is called from test.c and line is 14