• Stars
    star
    1,954
  • Rank 22,867 (Top 0.5 %)
  • Language
    Go
  • License
    MIT License
  • Created about 7 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⚖️ A tool for transpiling C to Go.

Build Status GitHub version Go Report Card codecov GitHub license Join the chat at https://gitter.im/c2goproject Twitter GoDoc

A tool for converting C to Go.

The goals of this project are:

  1. To create a generic tool that can convert C to Go.
  2. To be cross platform (linux and mac) and work against as many clang versions as possible (the clang AST API is not stable).
  3. To be a repeatable and predictable tool (rather than doing most of the work and you have to clean up the output to get it working.)
  4. To deliver quick and small version increments.
  5. The ultimate milestone is to be able to compile the SQLite3 source code and have it working without modification. This will be the 1.0.0 release.

Installation

c2go requires Go 1.9 or newer.

go get -u github.com/elliotchance/c2go

Usage

c2go transpile myfile.c

The c2go program processes a single C file and outputs the translated code in Go. Let's use an included example, 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;
}
c2go transpile prime.c
go run prime.go
Enter a number
23
Prime number.

prime.go looks like:

package main

import "unsafe"

import "github.com/elliotchance/c2go/noarch"

// ... lots of system types in Go removed for brevity.

var stdin *noarch.File
var stdout *noarch.File
var stderr *noarch.File

func main() {
	__init()
	var n int
	var c int
	noarch.Printf([]byte("Enter a number\n\x00"))
	noarch.Scanf([]byte("%d\x00"), (*[1]int)(unsafe.Pointer(&n))[:])
	if n == 2 {
		noarch.Printf([]byte("Prime number.\n\x00"))
	} else {
		for c = 2; c <= n-1; func() int {
			c += 1
			return c
		}() {
			if n%c == 0 {
				break
			}
		}
		if c != n {
			noarch.Printf([]byte("Not prime.\n\x00"))
		} else {
			noarch.Printf([]byte("Prime number.\n\x00"))
		}
	}
	return
}

func __init() {
	stdin = noarch.Stdin
	stdout = noarch.Stdout
	stderr = noarch.Stderr
}

How It Works

This is the process:

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

  2. pp.c is parsed with the clang AST and dumps it in a colourful text format that looks like this. Apart from just parsing the C and dumping an AST, the AST contains all of the resolved information that a compiler would need (such as data types). This means that the code must compile successfully under clang for the AST to also be usable.

  3. Since we have all the types in the AST it's just a matter of traversing the tree in a semi-intelligent way and producing Go. Easy, right!?

Testing

By default only unit tests are run with go test. You can also include the integration tests:

go test -tags=integration ./...

Integration tests in the form of complete C programs that can be found in the tests directory.

Integration tests work like this:

  1. Clang compiles the C to a binary as normal.
  2. c2go converts the C file to Go.
  3. The Go is built to produce another binary.
  4. Both binaries are executed and the output is compared. All C files will contain some output so the results can be verified.

Contributing

Contributing is done with pull requests. There is no help that is too small! :)

If you're looking for where to start I can suggest finding a simple C program (like the other examples) that does not successfully translate into Go.

Or, if you don't want to do that you can submit it as an issue so that it can be picked up by someone else.

More Repositories

1

pie

🍕 Enjoy a slice! A utility library for dealing with slices and maps that focuses on type safety and performance.
Go
1,655
star
2

orderedmap

🔃 An ordered map in Go with amortized O(1) for Set, Get, Delete and Len.
Go
614
star
3

sshtunnel

🚇 Ultra simple SSH tunnelling for Go programs.
Go
253
star
4

vsql

✌️ Single-file or PostgreSQL-server compatible transactional SQL database written in pure V.
V
236
star
5

dingo

🐺 Easy, fast and type-safe dependency injection for Go.
Go
185
star
6

redismock

🕋 Mocking Redis in unit tests in Go.
Go
139
star
7

tf

✔️ tf is a microframework for parameterized testing of functions and HTTP in Go.
Go
136
star
8

pepper

🌶️ Create reactive frontends without ever writing frontend code.
Go
110
star
9

phpserialize

📑 PHP serialize() and unserialize() for Go
Go
108
star
10

mbzdb

🎵 Port of the MusicBrainz database to run on other RDBMSs with replication (previously named MB_MySQL.)
Perl
88
star
11

gedcom

👪 A Go library and CLI tools for encoding, decoding, traversing, merging, comparing, querying and publishing GEDCOM files.
Go
72
star
12

ghost

👻 Locate and fix overly complex lines of code in Go.
Go
53
star
13

concise

✅ Concise is test framework for using plain English and minimal code, built on PHPUnit.
PHP
47
star
14

CollectionFactory

🏭 Translation between native collections in Objective-C and serialized formats like JSON.
Objective-C
41
star
15

sqltest

📝 A comprehensive suite of SQL tests for testing the conformance of databases.
Python
39
star
16

bento

🍱 bento is an English-based automation language designed to be used by non-technical people.
Go
32
star
17

redis-usage

👁️ A non-blocking way to count the number of keys or size of Redis key prefixes
Go
30
star
18

vlang-sublime

Sublime Text support for the V programming language
Python
29
star
19

reflect

🪞 Runtime reflection for V (vlang)
V
27
star
20

ok

🆗 - a strongly-duck-typed language.
Go
17
star
21

mocksqs

📤 In-memory implementation of SQS ideal for unit testing.
Go
12
star
22

sqlite3x

100% compatible sqlite3 fork with more features
C
10
star
23

gedcompare

Compare GEDCOM files
Python
9
star
24

go-named-params

Named parameters for Go functions
Go
9
star
25

testify-stats

🔢 testify: print test and assertions statistics at the end of the test suite
Go
7
star
26

independentreserve

💸 PHP API for independentreserve.com
PHP
6
star
27

tesseract

🔳 tesseract is a SQL object database with Redis as the backend, think of it like a document store that you run SQL statements against.
Python
6
star
28

GoogleMusicClient

🎶 Google Music Client in Objective-C
Objective-C
6
star
29

tui

🎨 Simple Go library for building complex text user interfaces
Go
5
star
30

wikitranslate

Easier translation of Wikipedia pages with CAT tools.
Go
5
star
31

multiselector

Multi Selector for Paw
JavaScript
4
star
32

iterator

Iterator builders for PHP
PHP
4
star
33

postgresql-partitioning

🖖 Automatic tools for managing partitions
4
star
34

switch-check

Validate switch statements contain all enum values.
Go
4
star
35

jsonrpc

💬 Simple JSON-RPC server for Go
Go
3
star
36

vscode-ok

Language highlighting for the ok programming language in VSCode
2
star
37

tracklist-editor

A tool for editing track lists
JavaScript
2
star
38

sql2mql

☕ Pure coffeescript SQL to MongoDB statement parser.
CoffeeScript
2
star
39

eagle

🦅 Eagle is a highly parallel column-oriented embedded SQL database engine.
C
2
star
40

chartbrainz

The unofficial way to view charts from MusicBrainz.
Vue
2
star
41

Z

🇿Java to native C compiler.
Java
2
star
42

Hoard

🐿️ A PSR-compliant caching library for holding objects in nested pools with scripting ability.
PHP
2
star
43

Sentinel

Non-blocking Java web server.
Java
2
star
44

dandy

🔬 The handy, dandy test generation tool for Go.
Go
2
star
45

play.getok.dev

🕹️ play.getok.dev
HTML
1
star
46

maven

⚚ maven programming language
C++
1
star
47

Pluralizer

Objective-C Library/Cocoa Pod for Simple String Pluralization
Objective-C
1
star
48

csv

Reading and writing CSV files in OK.
1
star
49

delta

🔺 The fastest scripting language on the planet based on PHP (pre-alpha)
C
1
star
50

toy

🧸 A toy language
JavaScript
1
star
51

EagleDB

🐦 Concept column-oriented MVCC SQL daemon.
Java
1
star
52

construe

Language conversion and maintaining tool.
CoffeeScript
1
star
53

intuit-quickbooks

The PHP SDK for QuickBooks v3 is set of PHP classes that make it easier to call QuickBooks APIs.
PHP
1
star
54

independentreserve-python

Python API for independentreserve.com
1
star
55

codekata.io

Online and realtime Kata for TDD
PHP
1
star
56

rateyourmusic-todo

Discussion and queue for entities that need editing help
1
star