首页 > 解决方案 > Cgo 找不到像这样的标准库

问题描述

标签: c++gocgo

解决方案


cgo makes it very easy to wrap C with Go, but C++ is a bit different. You have to extern "C" the functions that you want to make a function-name in C++ have 'C' linkage, otherwise the linker won't see the function. So, the actual problem is in the C++ header file. If you can't change the C++ code because it's a library, you may have to write wrappers (example).

This will compile:

.
├── test.cpp
├── test.go
└── test.hpp

test.hpp

#ifdef __cplusplus
extern "C" {
#endif

    int test();
#ifdef __cplusplus
}
#endif

test.cpp

#include <iostream>
#include "test.hpp"
int test() {
    std::cout << "Hello, World! ";
    return 0;
}

test.go

package main

// #cgo CXXFLAGS: -I/usr/lib/
// #cgo LDFLAGS: -L/usr/lib/ -lstdc++
// #include "test.hpp"
import "C"

func main() {
    C.test()
}

Put the files in the same folder, run go build

Hello, World!


推荐阅读