Search code examples
cgo

Cannot import more libraries when using cgo


I'm attempting to re-write some Go code in C mainly as a learning experience, however I have ran into an issue to which I cannot find the answer to elsewhere.

I am attempting to run the following code:

package conv

/*
#include <stdio.h>
int** ConvertStringToArray(char* str){
    printf("%s\n", str);
}
*/

import (
    "C"
    "unsafe"
)

func ToArrayGo(str string) [][]int {
    return nil // TODO
}

func ToArrayC(str string) [][]int {
    C.ConvertStringToArray(C.CString(str))
    return nil // TODO
}

If I comment out the unsafe import it works just fine, however when I add it in I get the following error with the go install/test commands:

37: error: 'ConvertStringToArray' undeclared (first use in this function)

This is also the case whenever I try to import any other libraries. Any help would be appreciated or even a redirect to a relevant issue (I've already looked but may have missed one).

Thanks, Dave


Solution

  • import "C"
    

    should be a line unto itself, and the first import. Then you can

    import (
      "unsafe"
    )
    

    as the next line.