C++ 中的 __FILE__、__LINE__ 和 __FUNCTION__ 是什么


在这里,我们将了解 C++ 中 __FILE、__LINE__ 和 __FUNCTION__ 的含义。

__FILE__

此宏用于获取当前文件的路径。当我们需要创建日志文件时,这非常有用。以下代码将解释它的功能。

示例

#include<iostream>
using namespace std;
int errorLog (const char* file, const std::string& msg){
   cerr << "[" << file << "] " << msg << endl;
}
#define LOG( msg ) errorLog( __FILE__, msg )
main() {
   LOG("This is a dummy error");
}

输出

[D:\Misc C and C++ Questions\test_prog.cpp] This is a dummy error

__LINE__

此宏可以在源文件中找到当前行号。此行号为一个整数。当日志语句生成时,__LINE__ 会起到一些有用的作用。查看以下示例,了解其含义。

示例

#include<iostream>
using namespace std;
int errorLog (int line, const std::string& msg){
   cerr << "[" << line << "] " << msg << endl;
}
#define LOG( msg ) errorLog( __LINE__, msg )
main() {
   LOG("This is a dummy error");
}

输出

[12] This is a dummy error

__FUNCTION__

此宏可以返回当前函数。当日志语句生成时,__FUNCTION__ 会起到一些有用的作用。查看以下示例,了解其含义。

long double rintl(long double argument)

示例

#include<iostream>
using namespace std;
int errorLog (const char* func, const std::string& msg){
   cerr << "[" << func << "] " << msg << endl;
}
#define LOG( msg ) errorLog( __FUNCTION__, msg )
void TestFunction(){
   LOG("Send from Function");
}
main() {
   TestFunction();
   LOG("This is a dummy error");
}

输出

[TestFunction] Send from Function
[main] This is a dummy error

更新于: 2019-7-30

7K+ 次浏览

开启你的 事业

完成课程以获得认证

开始
广告
© . All rights reserved.