In a C++20 logging library, which jobs of a LOG macro can std::source_location take over, and which still need the preprocessor?
answer
- __FILE__ and __LINE__ at the call site
- a defaulted current() argument
- arguments run before the call
- #cond turns code into text
basics
~20 sstd::source_location::current() as a defaulted parameter captures the caller's file, line and function, replacing FILE and LINE. A macro is still needed to stringize an expression, to skip evaluating message arguments when a level is off, and to compile calls out entirely.
solid answer
~50 sClassic `LOG(...)` macros exist mainly to paste `__FILE__`, `__LINE__` and `__func__` at the call site. C++20's `std::source_location` does that in an ordinary function: give it a parameter `std::source_location loc = std::source_location::current()`, and the standard says a `current()` call in a default argument should report the location of the call that uses it. Combined with `std::format`, most logging can be plain, namespaced, type-checked functions. Three jobs still need the preprocessor. **Stringizing**: `#cond` turns a checked expression into text, which no function can see. **Lazy arguments**: a function's arguments are evaluated before the call, so `logx::debug(dump_state())` runs `dump_state()` even when debug output is off; a macro can wrap the call in `if (enabled)`, or the API must take a lambda. **Compiling out**: removing calls per build configuration with `#if`. Keep those macros thin and prefixed, delegating to functions.
code
cpp · 29 lines#include <cstdio>
#include <source_location>
#include <string>
namespace logx {
inline int threshold = 2; // runtime log level
// C++20: the default argument is evaluated at the call site.
inline void log(int level, const std::string& msg,
std::source_location loc = std::source_location::current()) {
if (level < threshold) return;
std::printf("%s:%u %s: %s\n", loc.file_name(), static_cast<unsigned>(loc.line()),
loc.function_name(), msg.c_str());
}
} // namespace logx
std::string expensive() { std::puts("expensive() ran"); return "state dump"; }
// Still a macro: stringize the condition and skip evaluating the message.
#define LOGX_CHECK(cond, msg) \
do { \
if (!(cond)) logx::log(3, std::string("check failed: ") + #cond + " " + (msg)); \
} while (0)
int main() {
logx::log(3, "started");
logx::log(1, expensive()); // filtered out, but expensive() already ran
LOGX_CHECK(1 + 1 == 2, expensive()); // condition true: expensive() never runs
}go deeper
Know that logging macros exist to capture FILE and LINE, and that C++20 adds std::source_location for the same purpose.
Explain how source_location::current() as a default argument reports the caller's location, and why arguments to a function are always evaluated before the call.
Show the remaining macro jobs, stringizing, lazy evaluation and compile-time removal, the parameter-pack pitfall with defaulted source_location and the struct workaround.
Decide the shape of a team's logging API: which parts are functions, which thin macros remain, and how they are named and compiled out across build configurations.
## What a logging macro was doing A typical pre-C++20 logging macro looks like `#define LOGX_INFO(msg) logx::write(__FILE__, __LINE__, __func__, (msg))`. It is a macro for one main reason: `__FILE__` and `__LINE__` are **predefined macros** that expand where they are written, so only a macro written at the call site can capture the caller's location. (`__func__` is a predefined variable inside each function body, not a macro, but it has the same constraint.) Everything else, the formatting, the level check and the output, could already be an ordinary function. ## What std::source_location takes over (C++20) The header `<source_location>` provides `std::source_location`, with `file_name()`, `line()`, `column()` and `function_name()`. Its static member `current()` is `consteval`, and the standard adds a rule that makes it useful for logging: a call to `current()` that appears as a **default argument** should correspond to the location of the invocation of the function that uses the default argument. ```cpp namespace logx { inline void info(const std::string& msg, std::source_location loc = std::source_location::current()) { std::printf("%s:%u %s ", loc.file_name(), static_cast<unsigned>(loc.line()), msg.c_str()); } } logx::info("started"); // reports this file and this line ``` That replaces `__FILE__`, `__LINE__` and `__func__` with a function that lives in a namespace, is type-checked and appears in a debugger. Some details: - `function_name()` returns an implementation-defined string; clang prints `int main()` where another implementation may print just `main`. - `line()` returns `std::uint_least32_t`, so cast it before passing it to `printf("%u")`. - A defaulted `source_location` parameter cannot follow a **function parameter pack**: `template<class... Args> void info(const char* fmt, Args&&... args, std::source_location loc = ...)` deduces the pack as empty, and clang reports `no known conversion from 'int' to 'std::source_location'`. The usual fix is a small struct holding the format string and a `source_location`, whose converting constructor has the defaulted `current()` argument; the string literal converts at the call site and captures the location there. ## What still needs the preprocessor | Job | Why a function cannot do it | Macro tool | |---|---|---| | print the text of a failed check | a function receives the value `false`, not the code that produced it | stringizing `#cond` | | skip evaluating expensive message arguments | arguments are evaluated before any function body runs | wrap the call in `if (level_enabled)` | | remove calls entirely from a build | the call and its arguments must not even be compiled | `#if LOGX_ENABLED` | | build unique names, e.g. a scoped timer variable | identifiers cannot be computed in C++ | token pasting `a##b` | The lazy-argument case is the one interviewers probe. In `logx::debug(dump_state())`, `dump_state()` always runs, even if `debug` returns immediately. Two ways out: 1. A thin macro: `#define LOGX_DEBUG(...) do { if (logx::debug_enabled()) logx::debug(__VA_ARGS__); } while (0)`, which evaluates the arguments only when the level is on. 2. A lambda-taking API: `logx::debug([&] { return dump_state(); });`, which keeps everything in the language at the cost of noisier call sites. ## The macro that remains, written carefully A check macro that keeps the stringizing and the laziness but delegates everything else looks like this: ```cpp #define LOGX_CHECK(cond, msg) do { if (!(cond)) logx::log(3, std::string("check failed: ") + #cond + " " + (msg)); } while (0) ``` - `#cond` turns the tokens of the condition into a string literal, so the log shows `1 + 1 == 2` rather than `false`. - `msg` is evaluated only when the check fails, so an expensive message costs nothing on the success path. - The `do { ... } while (0)` wrapper makes the macro behave as one statement after an `if`; the general reasons belong with macro expansion in general. - `logx::log` still receives the caller's location through its defaulted `source_location` parameter, because the macro expands at the call site. ## Designing the hybrid A modern logging library usually ends up with: - **functions** carrying the real logic, taking a `source_location`, in a namespace; - **a few thin macros**, upper-case and prefixed (`LOGX_CHECK`, `LOGX_DEBUG`), only where stringizing, laziness or compile-time removal is required, each delegating to a function; - the macros guarded so they can be compiled out with one configuration macro. Before C++20, or on a library without `__cpp_lib_source_location`, the location still comes from `__FILE__` and `__LINE__` through a macro; the feature-test macro `__cpp_lib_source_location` (201907L) lets one header support both. ## Interview summary - `std::source_location::current()` as a default argument captures the caller's location in a function. - Macros remain for stringizing, lazy argument evaluation, compile-time removal and token pasting. - Keep remaining macros thin, prefixed and delegating to real functions.
- Why can't a variadic logging function take std::source_location as a defaulted last parameter?A function parameter pack that is not the last parameter is not deduced from trailing arguments, so the pack is deduced as empty and every argument is matched against the parameters after it. The call then tries to convert the first message argument to std::source_location and fails. Wrapping the format string in a struct whose constructor takes the defaulted current() argument moves capture to the conversion at the call site.
- How can a logging API avoid evaluating expensive arguments without any macro?Take a callable instead of a value, for example logx::debug([&] { return dump_state(); }). The library checks the level first and invokes the lambda only when the message will be written. The cost is a noisier call site and a lambda per call, which is why many libraries keep a thin macro for the common case.
- A function with a source_location parameter reports the line of its own definition
- std::source_location removes every reason to write a logging macro
- Function arguments are evaluated only if the function body uses them
- __func__ is a macro like __FILE__
- function_name() returns the same text on every implementation
Assumes C++20 for std::source_location and std::format; before C++20 the caller's location is only available through the __FILE__ and __LINE__ macros.