1.13 does not run init() when cgo is imported

138 views
Skip to first unread message

Graham Nicholls

unread,
Jan 21, 2020, 8:24:27 AM1/21/20
to golang-nuts
I have the following code:

  3 /*
  4   selinux.go - return the sestatus
  5
  6
  7   The lines below are preamble to the import of "C" -
  8   they should be left untouched
  9 */
 10
 11 // //cgo  linux CFLAGS: -Iinclude -I.
 12 // #cgo pkg-config: libselinux
 13 // #include <selinux/selinux.h>
 14 // #include <selinux/label.h>
 15 // #include <stdlib.h>
 16 // #include <stdio.h>
 17 // #include <sys/types.h>
 18 // #include <sys/stat.h>
 19
 20 import "C"
 21 import (
 22   "fmt"
 23   "net/http"
 24 )
 25
 26 const (
 27   Enforcing  = 1
 28   Permissive = 0
 29   Disabled   = -1
 30 )
 31
 32 func init() {
 33   if len(testFunctionsMap) == 0 {
 34     testFunctionsMap = make(funcPtrMap)
 35   }
 36   testFunctionsMap["selinux"] = SELinuxStatus
 37   initCtr++
 38 }

The program also has several other files all in package main. The init functions in those files do get called; this init function doesn't - "selinux" never gets added to the testFunctionsMap.

This used to work - I think on 1.9 was the previous version.  I've looked at the release notes, and it seems that work has been done on cgo - but I can't see anything which might explain this behaviour.  

Thanks.

Tamás Gulácsi

unread,
Jan 21, 2020, 8:38:20 AM1/21/20
to golang-nuts
What if you remove lines 33-35? Does it panic?

Maybe some other init function fills testFunctionsMap?
For maps, use a nil check before creation, not length check!

Ian Lance Taylor

unread,
Jan 21, 2020, 9:40:02 AM1/21/20
to Graham Nicholls, golang-nuts
It's odd that you have a blank line on line 19. That makes all those
directives ineffective. The cgo comment must immediately precede the
import "C", with no blank lines. Is this really the exact file that
you are compiling?

The other thing to consider is that if cgo is not enabled, then the go
tool will silently not build any Go files that import "C". And cgo is
not enabled by default when cross-compiling. Try setting
CGO_ENABLED=1 in the environment.

Ian

Graham Nicholls

unread,
Jan 21, 2020, 11:16:03 AM1/21/20
to golang-nuts
Mea Culpa.

I was building using a script; to get a solaris build I had disabled cgo.  Sorry to have wasted your time, and thanks for the responses - I would have updated sooner, but it as a new poster, it didn't appear immediately.
Reply all
Reply to author
Forward
0 new messages