在C11的新特性中,新增加了宏定義 __func__ 用來描述直接得到當函數的名稱。
如:
const char* hello() {return __func__;} //返回hello.
也可作為初始化參數傳遞如:
struct TestStruct {
TestStruct (): name(__func__){} //返回TestStruct結構體類型。
const char* name;
};
__VAR_ARGS__ 表示可變參數的宏串,如下
#define LOG(...) {\
fprintf(stderr, "%s: Line %d:\t", __FILE__, __LINE__);\
fprintf(stderr, __VA_ARGS__);\
fprintf(stderr, "\n");\
}
這樣就可以用一個宏實際了,標准輸出的行為了。
1 //demo.cpp 2 3 #include <iostream> 4 5 using namespace std; 6 7 const char* hello() {return __func__;} 8 const char* world() {return __func__;} 9 //====================1======================== 10 struct TestStruct { 11 TestStruct (): name(__func__){} 12 const char* name; 13 }; 14 //====================2======================== 15 #define LOG(...) {\ 16 fprintf(stderr, "%s: Line %d:\t", __FILE__, __LINE__);\ 17 fprintf(stderr, __VA_ARGS__);\ 18 fprintf(stderr, "\n");\ 19 } 20 //====================3======================== 21 int main(int argc, char **args){ 22 cout << "Standard Clib: " << __STDC_HOSTED__ << endl; 23 cout << "Standard C: " << __STDC__ << endl; 24 25 cout << "ISO/IEC " << __STDC_ISO_10646__ << endl; 26 cout << hello() << ", " << world() << endl; 27 //====================1======================== 28 TestStruct ts; 29 cout << ts.name << endl; 30 //====================2======================== 31 32 int x = 3; 33 LOG("x = %d", x); 34 35 //====================3======================== 36 37 38 39 40 return 0; 41 } 42 43 // gcc -std=c++11 demo.cpp -omain