goimports-reviser icon indicating copy to clipboard operation
goimports-reviser copied to clipboard

Incorrect behavior with cgo when only import "C" is used

Open kokororin opened this issue 1 month ago • 0 comments

When using cgo, the behavior can be incorrect if there is only an import "C" statement in the Go file.

Before:

package demo

/*
#include <stdlib.h>
#include "version.h"
*/
import "C"

// Version returns version string
func Version() string {
	return C.GoString(C.version())
}

After:

package demo

import "C"

func Version() string {
	return C.GoString(C.version())
}

One workaround for this issue is to add an underscore import after import "C". This ensures the correct behavior. Here is the modified code:

package demo

/*
#include <stdlib.h>
#include "version.h"
*/
import "C"
import (
	_ "fmt"
)

// Version returns version string
func Version() string {
	return C.GoString(C.version())
}

kokororin avatar May 27 '24 05:05 kokororin