https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68255
Bug ID: 68255 Summary: cgo-generated constructor not being called Product: gcc Version: 6.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: go Assignee: ian at airs dot com Reporter: vogt at linux dot vnet.ibm.com CC: cmang at google dot com Target Milestone: --- Host: s390x Target: s390x Created attachment 36669 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=36669&action=edit Test case With the latest code from the Gcc-6 development branch, constructor functions in packages may not be called. (Test code attached, run with $ tar xf cgo-ling.tar $ cd cgo-link $ GOPATH=$(pwd) $ cd src/main $ go build $ ./cgo-link" ==> NULL pointer acces, crash .) -- src/main/main.go -- package main import "pack" func main () { pack.Foo() } -- END -- -- src/pack/pack.go -- package pack /* #include "c/c_code.c" */ import "C" func Foo () { println(C.p_cfunc) } -- END -- -- src/pack/c/c_code.c -- #include <stdio.h> typedef void (*cfunc_t)(void); static void cfunc(void) { printf("hallo\n"); } const cfunc_t p_cfunc = cfunc; -- END -- The init function generated by cgo to initialize p_cfunc is not placed into the executable: $ go build -x -- snip -- ... ar cru $WORK/libpack.a $WORK/pack/_obj/_go_.o $WORK/pack/_obj/_cgo_defun.o $WOR\ K/pack/_obj/_cgo_export.o $WORK/pack/_obj/pack.cgo2.o ... .../bin/gccgo -I $WORK -I .../cgo-link/pkg/gccgo_linux_s390x -c -g -fgo-relativ\ e-import-path=_.../cgo-link/src/main -o $WORK/main/_obj/_go_.o ./main.go ar cru $WORK/libmain.a $WORK/main/_obj/_go_.o .../bin/gccgo -o $WORK/main/_obj/exe/a.out $WORK/main/_obj/_go_.o -Wl,-( $WORK/\ libpack.a -Wl,-) -Wl,-E cp $WORK/main/_obj/exe/a.out main -- snip -- The linker invocation triggered with the final gccgo command disposes of the init() function generated by cgo, so p_cfund ends up unitinialised. The problem goes away if I put _go_.o into the link group with libpack.a. While it's possible to do the same in C, the specific problem with the go tool and cgo is that you have no direct control over the linker invocation. I'm not sure whether this is a bad invocation of the linker or a bug in the linker, but it should be possible to fic that in the sources of the go tool in build.go. -- This is probably the same problem as here: /show_bug.cgi?id=65134 But the workaround mentioned there won't work because the init function is generated by cgo.