Image for post
Image for post

Recently I started writing a tool for converting C to Go.

I created this project as a proof of concept. It is written in python and uses the python clang bindingsto do the vast majority of the hard work.

Real Example

One of the examplesin the repository is prime.c:

#include <stdio.h>int main()
{
int n, c;
printf("Enter a number\n");
scanf("%d", &n);
if ( n == 2 )
printf("Prime number.\n");
else
{
for ( c = 2 ; c <= n - 1 ; c++ )
{
if ( n % c == 0 )
break;
}
if ( c != n )
printf("Not prime.\n");
else
printf("Prime number.\n");
}
return 0;
}

Execute:

python c2go.py tests/prime.c

Will produce:

package mainimport (
"fmt"
)
// ... lots of system types in Go removed for brevity.func main() {
var n int
var c int
fmt.Printf("Enter a number\n")
fmt.Scanf("%d", &n)
if n == 2 {
fmt.Printf("Prime number.\n")
} else {
for c = 2; c <= n - 1; c += 1 {
if n % c == 0 {
break
}
}
if c != n {
fmt.Printf("Not prime.\n")
} else {
fmt.Printf("Prime number.\n")
}
}
return
}

This is the process:

  1. The C code is preprocessed with clang. This generates a larger file, but removes all the platform specific directives and macros.

Testing

Testing is done with a set of integrations tests in the form of complete C programs that can be found in the tests directory.

For each of those files:

  1. Clang compiles the C to a binary as normal.

Feel Like Contributing?

As I said it is just a proof of concept (sorry for all the hacky Python).

Contributing is done with pull requests. If you’re looking a place to to start I can suggesting finding a simple C program (like the other examples) that does not successfully translate to Go and fixing up the Python so that it does.

Originally published at http://elliot.land on March 19, 2017.

Written by

I’m a data nerd and TDD enthusiast originally from Sydney. Currently working for Uber in New York. My thoughts here are my own. 🤓 elliotchance@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store