I am trying to get a variable value from a c++ code using cgo. For libraries ended in .h
all works fine, but for libraries like <iostream>
, <map>
, <string>
etc, I got the following error:
fatal error: iostream: No such file or directory
4 | #include <iostream>
| ^~~~~~~~~~
Below my code:
package main
/*
#cgo LDFLAGS: -lc++
#include <iostream>
std::string plus() {
return "Hello World!\n";
}
*/
import "C"
import "fmt"
func main() {
a := Plus_go()
fmt.Println(a)
}
func Plus_go() string {
return C.plus()
}
I added the #cgo LDFLAGS: -lc++
flag because I saw this recommendation on an answer here on stackoverflow at https://stackoverflow.com/a/41615301/15024997.
I am using VS Code (not VS Studio), windows 10, Go 1.18 (lastest version).
I ran the following commands go tool cgo -debug-gcc mycode.go
to trace compiler execution and output:
$ gcc -E -dM -xc -m64 - <<EOF
#line 1 "cgo-builtin-prolog"
#include <stddef.h> /* for ptrdiff_t and size_t below */
/* Define intgo when compiling with GCC. */
typedef ptrdiff_t intgo;
#define GO_CGO_GOSTRING_TYPEDEF
typedef struct { const char *p; intgo n; } _GoString_;
typedef struct { char *p; intgo n; intgo c; } _GoBytes_;
_GoString_ GoString(char *p);
_GoString_ GoStringN(char *p, int l);
_GoBytes_ GoBytes(void *p, int n);
char *CString(_GoString_);
void *CBytes(_GoBytes_);
void *_CMalloc(size_t);
__attribute__ ((unused))
static size_t _GoStringLen(_GoString_ s) { return (size_t)s.n; }
__attribute__ ((unused))
static const char *_GoStringPtr(_GoString_ s) { return s.p; }
#line 3 "C:\\Users\\Home\\OneDrive\\Desktop\\DevicesC++\\devices.go"
#include <iostream>
std::string plus() {
return "Hello World!\n";
}
#line 1 "cgo-generated-wrapper"
EOF
C:\Users\Home\OneDrive\Desktop\DevicesC++\devices.go:5:10: fatal error: iostream: No such file or directory
5 | #include <iostream>
| ^~~~~~~~~~
compilation terminated.
C:\Users\Home\OneDrive\Desktop\DevicesC++\devices.go:5:10: fatal error: iostream: No such file or directory
5 | #include <iostream>
| ^~~~~~~~~~
compilation terminated.