Search code examples
gocgo

Preprocessor flag to detect CGO build?


In a c file that's beside my go file and is compiled together via CGO, I'd like to check via preprocessor whether it's being compiled via go or not. I'd like to do this because, for example, I'd like to protect #include _cgo_export.h with #ifdef flags, since such header exists solely during compilation and I don't want my editor to warn about its absence.


Solution

  • From the documentation just do:

    // #cgo CFLAGS: -DWHATEVER_YOU_WANT_TO_INDICATE_CGO=1
    import "C"
    

    (or just -D FOO if you don't want a value) or set CGO_CFLAGS in the environment.

    You can see what is happening behind the scenes with go build -x. For me it shows -D GOOS_freebsd -D GOARCH_amd64 while compiling the cgo generated _cgo_defun.c file, but only for that file and not to my own *.c files. So I don't think there are any usable predefined preprocessor flags (and the documentation also doesn't mention any).