登录
首页 >  Golang >  Go问答

在 Visual Studio 2019 中连接到 Golang 代码的 C 项目

来源:stackoverflow

时间:2024-02-23 11:15:23 447浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《在 Visual Studio 2019 中连接到 Golang 代码的 C 项目》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我在 visual studio 2019 中有一个 c 项目,我想在其中使用用 go 编写的某些函数。

我有一个名为 ctest.go 的测试文件,其中包含以下内容:

package main

import (
    "c"
    "fmt"
)

//export printint
func printint(x int) {
    fmt.printf("hello from go: %d", x)
}

func main() {}

我正在使用此命令生成静态库:

go build -buildmode=c-archive ctest.go

我最终得到两个文件:ctest.actest.h,它们包含在我的 vs 项目中。我在代码中包含 ctest.h 并立即收到以下错误:

identifier "__size_type__" is undefined
expected a ';'
expected a ';'

生成的头文件包含导致它的以下行:

99258435538​​4

我用 size_t 替换了 __size_type__ 并只是注释掉了 _complex 行以停止错误。

现在我的 vs 项目编译时包含头文件。但是一旦我尝试像这样使用我的 go 函数:

printint(5);

我收到 2 个警告,然后出现 6 个错误:

Warning LNK4078 multiple '.text' sections found with different attributes (60600060)    AWO F:\AWO\AWO\ctest.a(go.o)
Warning LNK4078 multiple '.text' sections found with different attributes (60600060)    AWO F:\AWO\AWO\ctest.a(go.o)
Error   LNK2019 unresolved external symbol __imp___iob referenced in function __cgo_preinit_init    AWO F:\AWO\AWO\ctest.a(000005.o)
Error   LNK2001 unresolved external symbol __imp___iob  AWO F:\AWO\AWO\ctest.a(000006.o)
Error   LNK2001 unresolved external symbol __imp___iob  AWO F:\AWO\AWO\ctest.a(000007.o)
Error   LNK2019 unresolved external symbol _fprintf referenced in function _x_cgo_sys_thread_create AWO F:\AWO\AWO\ctest.a(000005.o)
Error   LNK2001 unresolved external symbol _fprintf AWO F:\AWO\AWO\ctest.a(000007.o)
Error   LNK1120 2 unresolved externals  AWO F:\AWO\Debug\AWO.exe    1

这就是我被困住的地方。我不确定我做错了什么,或者应该采取不同的做法才能正确使用 go 生成的库。


解决方案


  1. 项目属性 -> 链接器 -> 输入 -> 其他依赖项
  • legacy_stdio_definitions.lib;%(附加依赖项)
  • 添加源代码

    c

    file* __cdecl __iob_func(void)
    {
        file _iob[] = { *stdin, *stdout, *stderr };
        return _iob;
    }
    

    c++

    extern "C" { FILE __iob_func[3] = { *stdin,*stdout,*stderr }; }
    
  • 理论要掌握,实操不能落!以上关于《在 Visual Studio 2019 中连接到 Golang 代码的 C 项目》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

    声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
    相关阅读
    更多>
    最新阅读
    更多>
    课程推荐
    更多>