3

I am trying to run a C call from go language code. Here is the program I am running:

package main

// #include<proxy.h>

import "C"
import "fmt"

func main(){
    fmt.Println(C.CMD_SET_ROUTE)
}

Here is the content of the file proxy.h:

#ifndef PROXY_H
#define PROXY_H

#include <netinet/in.h>

#ifdef CMD_DEFINE
#   define cmdexport
#else
#   define cmdexport static
#endif

cmdexport const int CMD_SET_ROUTE = 1;
cmdexport const int CMD_DEL_ROUTE = 2;
cmdexport const int CMD_STOP      = 3;

Now, here is the error I am getting when trying to run that program:

pensu@ubuntu:~$ go run test.go 
# command-line-arguments
could not determine kind of name for C.CMD_SET_ROUTE

I am using gccgo-5 and go version 1.4.2. Could you please help me figure out what exactly is the issue here? TIA.

Pensu
  • 3,263
  • 10
  • 46
  • 71
  • I would avoid trying to use gccgo *and* go1.4.2. Stick with the default toolchain until you have a specific need for gccgo, to avoid added confusion. – JimB Jul 21 '15 at 14:49
  • 3
    There are lot of syntactic errors in your code. It would be better if you go through [this](http://blog.golang.org/c-go-cgo) blog post before using cgo. – Mayank Patel Jul 21 '15 at 17:03

1 Answers1

6

Four things:

  • You should be using double quotes when including proxy.h, as it resides in the same directory as your .go file.
  • There cannot be a blank line before you "C" comment and the "C" import.
  • You are missing an #endif at the end proxy.h.
  • You need to define CMD_DEFINE before including proxy.h. Otherwise, Go cannot access the static variable.

Below is the corrected code:

package main

// #define CMD_DEFINE
// #include "proxy.h"
import "C"
import "fmt"

func main(){
    fmt.Println(C.CMD_SET_ROUTE)
}
#ifndef PROXY_H
#define PROXY_H

#include <netinet/in.h>

#ifdef CMD_DEFINE
#   define cmdexport
#else
#   define cmdexport static
#endif

cmdexport const int CMD_SET_ROUTE = 1;
cmdexport const int CMD_DEL_ROUTE = 2;
cmdexport const int CMD_STOP      = 3;

#endif