Can I reliably get the file and line where a function is defined at runtime?

This was my attempt - Go Playground - The Go Programming Language

But for the function HelloBad(), I get the line of the return statement rather than the line of the function definition. If I disable go’s compiler optimizations via go run -gcflags -n I get the correct result for both. Is there another way to achieve the same without the extra compiler flags?

As far as I know, there are no other ways to disable inlining and compiler optimizations if you mean an equivalent of go:noinline directive and -l flag (compile command - cmd/compile - pkg.go.dev).

I’d use -gcflags '-N -l' instead of passing directives for each function. Are there any reasons for that?

It was just to demonstrate that the functions aren’t inlined

I wonder if there is a way to recalculate the correct lines without having to disable the compiler optimizations.

https://pkg.go.dev/runtime#Callers

CallersFrames accounts for inlined functions and adjusts the return program counters into call program counters. Iterating over the returned slice of PCs directly is discouraged, as is using FuncForPC on any of the returned PCs, since these cannot account for inlining or return program counter adjustment.

According to this CallersFrames() is supposed to account for inlining, but I tried using it and it had the same resutl as well:

    pc := reflect.ValueOf(Hello).Pointer()

    frame, _ := runtime.CallersFrames([]uintptr{pc}).Next()
    fmt.Printf("%+v %+v\n", frame.File, frame.Line)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.