Get Source Code Location Information in C++20

Get Source Code Location Information in C++20

In C++, capturing information about where a function is called can be extremely valuable for diagnostics, logging, and debugging. Details such as filename, line number, column, and function name help trace execution paths and identify issues more efficiently, especially in larger codebases.

Before C++20, obtaining this kind of metadata often relied on preprocessor macros like __FILE__, __LINE__, and __func__. While effective, these macros lacked type safety, were less flexible, and could make interfaces harder to design cleanly.

Since C++20, the std::source_location provides structured access to call-site information. By using the std::source_location::current() as a default argument, call-site information is captured automatically without additional boilerplate.

#include <iostream>
#include <source_location>

void log(const std::string_view message,
         const std::source_location location =
                 std::source_location::current()) {
    std::cout << location.file_name() << ":"
            << location.line() << ":"
            << location.column() << " '"
            << location.function_name() << "': "
            << message << std::endl;
}

int main() {
    log("Hello world");

    return 0;
}

Output example:

/home/john/myproject/main.cpp:15:8 'int main()': Hello world

Leave a Comment

Cancel reply

Your email address will not be published.