Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd/cgo: unsigned macros converted to signed equivalents #20369

Closed
bcmills opened this issue May 15, 2017 · 1 comment
Closed

cmd/cgo: unsigned macros converted to signed equivalents #20369

bcmills opened this issue May 15, 2017 · 1 comment

Comments

@bcmills
Copy link
Contributor

bcmills commented May 15, 2017

bcmills:~/src$ go version
go version devel +12f3099c7d Sat May 13 00:09:49 2017 -0400 linux/amd64
bcmills:~/src$ $(go env CC) --version
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4

My use-case is for checking conversions between Go types (such as int) and corresponding C types (such as C.size_t). I'm attempting to define a portable constant for SIZE_MAX:

const SizeMax = uint64(C.SIZE_MAX)

But that gives me a compile error. A simple whole program demonstrating the problem:

package main

/*
#include <limits.h>
#include <stdint.h>
*/
import "C"

import "fmt"

const SizeMax = uint64(C.SIZE_MAX)

func main() {
	fmt.Println(SizeMax)
}

with output:

bcmills:~/src$ go run sizemax/sizemax.go
# command-line-arguments
sizemax/sizemax.go:11[sizemax.cgo1.go:12:23]: constant -1 overflows uint64

A larger example program shows that the C constant is defined in C as a large unsigned number, but cgo is compiling it to the two's-complement signed constant:

package main

/*
#include <limits.h>
#include <stdint.h>

#define xstr(s) str(s)
#define str(s) #s

// size_max_str returns a C string containing the definition of SIZE_MAX.
static const char* size_max_str() {
	return xstr(SIZE_MAX);
}
*/
import "C"

import "fmt"

func main() {
	fmt.Println(C.GoString(C.size_max_str()))
	fmt.Println(C.SIZE_MAX)
}

Actual output:

bcmills:~/src$ go run sizemax/sizemax.go
(18446744073709551615UL)
-1

Expected:
Compile error, because the constant 18446744073709551615 overflows the default int type for integer constants.

(CC @ianlancetaylor @mdempsky; see also #4120 and #2470.)

@gopherbot
Copy link

CL https://golang.org/cl/43476 mentions this issue.

@golang golang locked and limited conversation to collaborators May 17, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants