Site Tools


hpp-source-location

Table of Contents

<source_location>

<source_location> provides std::source_location, which captures the filename, line number, column, and function name at the call site (C++20). It's useful for better error messages, logging, or assertions that show where they were invoked. Use it in library functions to provide context-aware diagnostics.

This example uses the default source_location parameter to capture the file and line number of each call site.

// compile: g++ -std=c++20 -o sourcelocationexample sourcelocationexample.cpp
// run: ./sourcelocationexample
// description: capture and print source location

#include <source_location>
#include <iostream>

void debug_info(std::source_location loc = std::source_location::current()) {
    std::cout << "called from " << loc.file_name() 
              << ":" << loc.line() << "\n";
}

int main() {
    debug_info();
    debug_info();
    
    return 0;
}
hpp-source-location.md · Last modified: