golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.65k stars 17.61k forks source link

cmd/cgo: fix C linker problems when linking C++ static libraries #40594

Open Keithcat1 opened 4 years ago

Keithcat1 commented 4 years ago

Currently, if I link a static library containing C++ files, Go can't tell the difference and uses the C linker for example gcc.exe (not g++.exe), which causes the standard C++ libraries to not be linked. I can think of 2 ways to fix this. Either add a "#cgo: c++" directive that tells Go that this is a C++ package, or just always use the C++ linker.

AlexRouSg commented 4 years ago

CGO only allows calling/using C code within Go, not C++. To use C++ code you need to create a C wraper, you can do that by adding a .cpp and a .h file with the C API into the package.

@ianlancetaylor I can't find any obvious place where this is explicitly pointed out, maybe it should?

ianlancetaylor commented 4 years ago

@AlexRouSg There is a hint at https://golang.org/cmd/go/#hdr-Calling_between_Go_and_C.

@Keithcat1 Perhaps you could use something like CC=g++. But I'm not quite picturing the problem. Do you have an archive that contains C++ file but also provide a pure C interface, and you are using cgo to call the pure C interface?

Keithcat1 commented 4 years ago

Yes, my situation is that I'm statically linking C++ libraries that come with a C API, then using the C API to call into that package. Actually setting CC=g++ could work, but I'd prefer a solution where I don't have to set something special every time I compile a C++ package using CGO. Plus, if that works, there's no reason to not use g++ by default anyway.

AlexRouSg commented 4 years ago

@Keithcat1 Try adding a empty .cpp file maybe with the include lines.

If that doesn't help, please provide more info by filling out the issue template that was shown when making a new issue. And provide the actual linker errors.