- 1 year ago
cgo on windows : naming of loaded dll
In Go, when using the cgo tool to call C code from Go, you can load and use shared libraries (DLLs on Windows) with the import "C"
statement. By default, cgo will use the naming convention for DLLs based on the platform. On Windows, it will add the .dll
extension to the library name.
For example, if you have a C library named mylibrary
, you can load it in Go using cgo like this:
gopackage main
import "C"
func main() {
// Your Go code here
}
In this case, cgo will look for a DLL named mylibrary.dll
in the system's search path.
If the DLL has a different name or is located in a specific directory, you can use the #cgo
directive to specify the library name and path.
For example, if your DLL is named mylibrary_custom.dll
and is located in the C:\mylibs
directory, you can load it like this:
gopackage main
/*
#cgo CFLAGS: -IC:/mylibs/include
#cgo LDFLAGS: -LC:/mylibs -lmylibrary_custom
*/
import "C"
func main() {
// Your Go code here
}
With the #cgo
directive, you can specify additional compiler and linker flags to control how cgo builds and links the C code in your Go program. In this case, we specify the include path with -IC:/mylibs/include
and the library path and name with -LC:/mylibs -lmylibrary_custom
.
Make sure to adjust the paths and names in the #cgo
directive to match the location of your DLL.
Note that on Windows, you may also need to set the CGO_ENABLED
environment variable to 1
to enable cgo:
bashset CGO_ENABLED=1
go build
By default, cgo is enabled on systems where it is required, such as Windows, and you don't need to explicitly set CGO_ENABLED
in those cases. However, it's good to be aware of this setting if you encounter any issues related to cgo on Windows.