Tuesday Coding Tip 09 — Source location

posted Originally published at medium.com 1 min read

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


If you want to log a filename and line number prior to C++20, you need to use the likes of __FILE__ and __LINE__ macros. To use those easily, you have to create a wrapper macro for logging, which usually leads to an ugly macro bonanza.

#include <iostream>
#include <format>

void log(
    const std::string& message,
    const std::string& fileName = __FILE__,
    unsigned lineNo = __LINE__)
{
    std::cout << std::format(
        "{}({}): {}\n",
        fileName,
        lineNo,
        message);
}

#define LOG(msg) log(msg, __FILE__, __LINE__)

int main()
{
    log("hello world");
    // logs: example.cpp(7): hello world
    // Note that __FILE__ and __LINE__ are expanded at their
    // position, not at the callsite
    LOG("hello world2");
    // logs: example.cpp(22): hello world2
    // Wrapping the call in another macro with explicit placement
    // of __FILE__ and __LINE__ makes them expand at the correct place
}

C++20 introduces std::source_location, a regular object that can be constructed as a default value of a logging function parameter and passed along as the user needs.

#include <iostream>
#include <source_location>
#include <format>

void log(
    const std::string& message,
    std::source_location location = std::source_location::current())
{
    std::cout << std::format(
        "{}({}) {}: {}\n",
        location.file_name(),
        location.line(),
        location.function_name(),
        message);
}

int main()
{
    log("hello world");
    // logs: example.cpp(19) int main(): hello world
}

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelskiverified - Apr 23
chevron_left

Related Jobs

Commenters (This Week)

6 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!