doudun1029 2014-10-16 18:09
浏览 111
已采纳

调用c函数时,“ import fmt”,“ import C”的顺序导致生成错误,为什么?

I have the following simple test go code : call_c.go

package main

/*
int getData(int *p, int n )
{
     int i; 
     for(i=0;i<n;i++) {
        p[i]=i;
    } 
    return n;
}
*/
import "C"
import "fmt"

func main() {
    var a [5]int32
    i := C.getData((*C.int)(&a[0]), 5)
    fmt.Println(i, a)
}

I use "go build call_c.go" to build the program and that builds fine.

But I found that if I simplely reverse the order of "import fmt", "import C" or add a newline between the C /* */ block code and the first import statement, the "go build call_c.go" command will return an error:

go build call_c.go
37: error: 'getData' undeclared (first use in this function)

Questions for expert gophers out there:

Why is the order of import important in go?

Why can't I add space between C block and the first import statement?

If I see this kind of error again, how best to debug it?

  • 写回答

2条回答 默认 最新

  • duangu4943 2014-10-16 18:18
    关注

    The order of import arn't generally important. But import "C" is very special when using cgo.

    From the docs:

    If the import of "C" is immediately preceded by a comment, that comment, called the preamble, is used as a header when compiling the C parts of the package. For example:

    // #include <stdio.h>
    // #include <errno.h>
    import "C"
    

    So, if you have a newline between your comment which contain the C code, and the import "C" , then the comment is just another comment, and isn't processed by cgo.

    Similarly if you reverse the order of import:

    /*
    int getData(int *p, int n )
    {
         int i; 
         for(i=0;i<n;i++) {
            p[i]=i;
        } 
        return n;
    }
    */
    import "fmt"
    import "C"
    

    The code in the comment is just another comment and isn't processed by cgo since it isn't immediately followed by an import "C". (or rather, import "C" isn't preceded by a comment)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算