3

I have created a golang program to pass some values to c program. I used this example to do so

My simple golang code :

package main

import "C"

func Add() int {
        var a = 23
        return a 
 }
func main() {}

Then I compiled this using go build -o test.so -buildmode=c-shared test.go

My C code :

#include "test.h"

int *http_200 = Add(); 

When I try to compile it using gcc -o test test.c ./test.so

I get

int *http_200 = Add(); ^ http_server.c:75:17: error: initializer element is not constant

Why I am getting this error? How to initialize that variable properly in my C code.

PS : edited after first comment.

1
  • 4
    The Go function Add returns a plain int value. In your C code you assign that value to a pointer to int? And please try to make a minimal reproducible example of the C program, copy-paste the full and complete output of the build, and also tell us how you build. Commented Jul 12, 2019 at 8:18

1 Answer 1

4

There are a couple of issues here. First is the incompatibility of the types. Go will return a GoInt. Second issues is that the Add() function has to be exported to get the desired header file. If you don't want to change your Go code, then in C you have to use the GoInt which is a long long.

A complete example is:

test.go

package main

import "C"

//export Add
func Add() C.int {
    var a = 23
    return C.int(a)
}

func main() {}

test.c

#include "test.h"
#include <stdio.h>

int main() {
    int number = Add();
    printf("%d\n", number);
}

Then compile and run:

go build -o test.so -buildmode=c-shared test.go
gcc -o test test.c ./test.so &&
./test

23


A second example using the GoInt: test.go

package main

import "C"

//export Add
func Add() int { // returns a GoInt (typedef long long GoInt)
    var a = 23
    return a
}

func main() {}

test.c

#include "test.h"
#include <stdio.h>

int main() {
    long long number = Add();
    printf("%lld\n", number);
}

Then compile and run:

go build -o test.so -buildmode=c-shared test.go
gcc -o test test.c ./test.so &&
./test

23

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is what I wanted to know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.