LoginSignup
10
8

More than 5 years have passed since last update.

[T.B.D.]C++で実行中に変数名を取得したい

Last updated at Posted at 2014-01-19

後日改訂予定。#一部私情により記述削除

C++で変数名を取得する。

実行時に構造体などの変数名を知りたかったため。

#include <iostream>
#include <stdio.h>
#include <string.h>

// For get variable name.
#define TO_STRING(VariableName) # VariableName
static const int MAXLENGTH = 256;

typedef struct {
    char charArray[MAXLENGTH];
} FooStructure;

typedef struct {
    int value;
    FooStructure fooSt;
    FooStructure *pFooSt;
} TestMacroStructure;

int main(int argc, char *argv[]) {
    int value = 3;

    // Get variable name
    std::string str = TO_STRING(value);

    // Display variable name.
    std::cout << str << std::endl;
    TestMacroStructure checkMacro;
    std::cout << TO_STRING( checkMacro.value) << std::endl;
    std::cout << TO_STRING( checkMacro.fooSt) << std::endl;
    std::cout << TO_STRING( checkMacro.fooSt.charArray) << std::endl;
    std::cout << TO_STRING( checkMacro.pFooSt->charArray) << std::endl;


    return 0;
} 

make後の出力結果は以下の通り。

budougumi0617@SERVER:~/> ./getVariableName
value
checkMacro.value
checkMacro.fooSt
checkMacro.fooSt.charArray
checkMacro.pFooSt->charArray

参考URL

変数名取得マクロ

http://faithandbrave.hateblo.jp/entry/20071116/1195228361

10
8
3

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
10
8