Loading packages which import "C"

557 views
Skip to first unread message

Sarita Singh

unread,
Jul 16, 2023, 12:48:15 PM7/16/23
to golang-nuts
I am trying to build static call graph of go project using cha package. However when there is a go file which imports "C", the packages.Load(cfg, args...) function returns error as it is not able to load such packages. The config struct is:
cfg := &packages.Config{
Mode:       packages.LoadSyntax | 4096,
Tests:      false,
Dir:        "",
BuildFlags: []string{"-tags=cgo=1"},
}
Can someone help me out with the BuildFlags field so that it can successfully load packages with "C" imports.
The error currently is:
go list failed to return CompiledGoFiles. This may indicate failure to perform cgo processing; try building at the command line. See https://golang.org/issue/38990.

Alan Donovan

unread,
Jul 17, 2023, 11:09:55 PM7/17/23
to golang-nuts
Hi Sarita,

go/packages usually has no trouble loading packages that import "C": underneath, it calls "go list -json" which generates Go code, and that's what we load and parse. Of course, that means you see the same (generated) Go code as the compiler, which is not what the user actually typed in their editor or committed to version control.

If you're using the CHA package, you'll need LoadAllSyntax, since the analysis requires source code for entire program. But you shouldn't need the "| 4096" to set hidden bits. (I wasn't even aware of that particular one, and I used this package regularly to load programs that import "C".)

I suggest you follow the example of one of the existing tools in the x/tools repo, such as cmd/callgraph:
or internal/cmd/deadcode:
https://cs.opensource.google/go/x/tools/+/master:internal/cmd/deadcode/deadcode.go;l=96

If that doesn't work, could you post a complete program that illustrates the problem? Or file a GitHub issue "x/tools" in the subject line? Thanks.

cheers
alan
Reply all
Reply to author
Forward
0 new messages