Living without a preprozessor...(cleanup code used for debugging, finding definitions in zigs files)

The C-Macros LINE and FILE can be replaced in zig with access to the @src function.
I found @src().line, @src().column by reading online and @src().file by experimenting.

At every position in the code, where this information should be available, I had to add something like
print( “LINE:{d}\n”,.{@src().line});
print( “COLUMN:{d}\n”,.{@src().column});
print( “FILE:{s}\n”,.{@src().file});

which clearly shows my intend but interrupts the reading of the part of the code, which is used for
“the real thing” (not for debugging that is).

Defining a function with these three lines and calling that function instead forbids itself for obvious reasons.

In C I would had hacked together a macro and the preprocessor would have done the rest for me.

How can I solve this dilemma in Zig?

Cheers!
Tuxic

One idea would be to make the function take a SourceLocation struct (the type returned by @src()) and do the printing and other debug stuff using the info from the given struct. The call site would then contain just the function call with a single @src call as an argument, like myDebugStuff(@src());. Fun fact, from what I’ve read on the relevant github issues, the function’s name is so short to better support this exact usecase.

edit: The below paragraph is wrong, please disregard it.

Also note that while the SourceLocation’s .file and .fn_name fields are comptime (compile time known), .line and .column are not. This should not be a problem with your setup, but it might be worth keeping in mind.

1 Like

Hi 1ynx,

I appreciate your help very much - yes, this kind of call is exactly what I was searching for ! :slight_smile:
Out of curiosity Why is fname/file comptime and column/line is not? I am asking because from my point of view all values are known at comptime…

I just double checked and in the current implementation all fields are comptime known. Apparently I read it wrong. It may change in the future, but it’s only a proposal for now. Sorry about the confusion.

1 Like

Hi 1ynx,

I like this kind of “”“confusion”“” (it was no confusion at all…it only triggered my curiosity… :wink: ) -
learned something new!

Cheers!
Tuxic

1 Like