Is it possible from Go app to detect if CGO_ENABLED?
Asked Answered
C

1

5

My Go app can work with MySQL, Postgres, and SQLite. At the first start, it asks what DB should be used.

SQLite works only with CGo. Depending on whether it is enabled or not, SQLite should be displayed in a list of supported databases.

Is it possible for the Go app to detect if CGO_ENABLED=1?

Counterstroke answered 2/12, 2020 at 7:38 Comment(0)
G
7

Use build constraints to detect CGO. Add these two files to the package:

cgotrue.go:

//go:build cgo
    
package yourPackageNameHere
    
const cgoEnabled = true

cgofalse.go:

//go:build !cgo
    
package yourPackageNameHere
    
const cgoEnabled = false

Only one of the files is compiled. Examine the cgoEnabled const to determine of CGO is enabled.

Another option is to add the following to a file that's always compiled:

var drivers []string{ "MySQL", "Postgres"}

and this to a CGO only file:

//go:build cgo

package yourPackageNameHere
    
func init() {
      drivers = append(drivers, "SQLite")
}
Gamogenesis answered 2/12, 2020 at 8:17 Comment(1)
Updated this to use current //go:build syntax, which has been there since go 1.17Garrido

© 2022 - 2024 — McMap. All rights reserved.