Search code examples
gccassemblygopackagecgo

Assembler used by golang when building with and without cgo


Let's say I have a golang package, which contains some assembly code:

 demopkg/
   source1.go
   source2.go
   asm_amd64.s

If I try to build it using go build, toolchain will use go tool asm to assemble the *.s files.

But if I add Cgo to the mixture, by putting a single import "C" into any of the sources, go will switch to gcc assembler.

I can see it by executing go build -n. Calls to the /usr/local/go/pkg/tool/linux_amd64/asm from the first case get replaced by calls to gcc. Besides that, it starts complaining about broken syntax.

Is this behaviour documented, so I can rely on it for the maintaining of my package? Can I force go build to use one exact assembler?


Solution

  • Yes, it's in the cgo documentation

    When the Go tool sees that one or more Go files use the special import "C", it will look for other non-Go files in the directory and compile them as part of the Go package. Any .c, .s, or .S files will be compiled with the C compiler. Any .cc, .cpp, or .cxx files will be compiled with the C++ compiler. Any .h, .hh, .hpp, or .hxx files will not be compiled separately, but, if these header files are changed, the C and C++ files will be recompiled. The default C and C++ compilers may be changed by the CC and CXX environment variables, respectively; those environment variables may include command line options.