Search code examples
gocgo

Is it possible from Go app to detect if CGO_ENABLED?


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?


Solution

  • 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")
    }