stdsource_location

std::source_location

简介

source_location​​ 类表示关于源码的具体信息,例如文件名、行号以及函数名。以前,希望获得关于调用位置的信息(用于记录、测试或调试目的)的函数必须使用宏,以令如 ‘​「LINE」​’ 与 ‘​「FILE」​’以及‘​「FUNCTION」​’ 的预定义宏于调用方的环境展开。source_location​​ 类提供更好的替代。

语言版本

「C++20」

头文件

#include <source_location>

示例

#include <iostream>
#include <string_view>
#include <source_location>
 
void log(std::string_view message,
         const std::source_location& location = std::source_location::current())
{
    std::cout << "info:"
              << location.file_name() << ':'
              << location.line() << ' '
              << message << '\n';
}
 
int main()
{
    log("Hello world!");
}

输出

info:main.cpp:16 Hello world!

常用方法

line 返回此对象所表示的行号
column 返回此对象所表示的列号
file_name 返回此对象所表示的文件名
function_name 返回此对象表示的函数名,若它存在

相关

C++20 之前的方式

#include <iostream>
#include <string_view>

void log(std::string_view message,
         std::string_view filename, int line)
{
  std::cout << "info:"
            << filename << ':'
            << line << ' '
            << message << '\n';
}

int main()
{
  // 必须在这里进行宏展开
  log("Hello world!", __FILE__, __LINE__);
}
// 输出
// info:main.cc:16 Hello world!

尝试以下代码

#include <iostream>
#include <string>
void log(std::string_view message, const std::string &filename = __FILE__, int line = __LINE__)
{
  std::cout << "info:"
            << filename << ':'
            << line << ' '
            << message << '\n';
}

int main()
{
  // 是你期望的结果吗
  log("Hello world!");
}
// main.cc:3 Hello world!

实际上,宏定义在编译期的预处理阶段就已经展开了,也就是定义log函数的哪一行。

拓展

C/C++ 程序由源程序变为可执行文件的几个阶段是:

  • 预处理阶段,由预处理器对程序文本中的宏进行展开。
  • 编译阶段,由编译器对经过预处理后的程序进行编译,编译过程形成的是汇编文件
  • 汇编阶段,目标文件里都是机器可以理解的二进制代码。
  • 链接阶段,则链接器对目标文件和用到的函数库文件进行链接,生成可执行文件。

posted @ 2023-10-03 19:32  天空之城00  阅读(176)  评论(0)    收藏  举报