SlideShare a Scribd company logo
1 of 22
Marcin Pasinski
Mender.io
Develop your Embedded Applications Faster:
Comparing C and Golang
My view on C vs Go
● I think Go is great and very
productive programming language
● It excels when developing
networking code
● I’m not considering it a
replacement or competitor for C
● Among the other things garbage
collection alone ensures that
Who am I?
● Marcin Pasinski
○ 10+ years in software development
○ M. Sc., Electronics and Telecommunication
○ marcin.pasinski@northern.tech
■ OTA updater for Linux devices
■ Integrated with Yocto
■ Open source (Apache v2 license)
■ Written in Go
■ Configuration management tool
■ Open source (GPL v3 license)
■ Written in C
Agenda
● Why did we choose go
● Go basics for Embedded development
● Code samples
● Demo
Language requirements
1. “External impact”
○ Size requirements on device
○ Setup requirement in Yocto Project
○ Possibility to compile for multiple platforms
2. “Internal considerations”
○ Competences in the company
○ Code share/reuse
○ Development speed
○ Access to common libraries (JSON, SSL, HTTP)
○ “Automatic memory management”
○ “Security enablers” (buffer overflow protection, etc.)
Language comparison
C C++ Go
Size requirements in devices Lowest Low (1.8MB more) Low (2.1 MB more, however will increase
with more binaries)
Setup requirements in Yocto None None Requires 1 layer (golang)*
Competence in the company Good Have some long time users Only couple of people know it
Buffer under/overflow protection None Little Yes
Code reuse/sharing from CFEngine Good Easy (full backwards compatibility) Can import C API
Automatic memory management No Available, but not enforced Yes
Standard data containers No Yes Yes
JSON json-c jsoncpp Built-in
HTTP library curl curl Built-in
SSL OpenSSL OpenSSL Built-in
* Go is natively supported by Yocto Project from Pyro release (Yocto 2.3)
Yocto build comparison
C C++ C++/Qt Go ...
Pure image size 8.4MB 10.2MB 20.8MB* 14.6MB
Size with network stack 13.4MB
(curl)
15.2MB
(curl)
20.8MB* 14.6MB
Shared dependencies Yes Yes Yes No/Maybe
Extra Yocto layer needed No No Yes Yes**
Deployment complexity Binary Binary Binary + Qt Binary
* Required some changes to upstream Yocto layer
** Go is natively supported by Yocto from Pyro release (Yocto 2.3)
Why did we pick up Go?
1. Golang has lots of core language features and libraries that allows much faster
development of applications.
2. The learning curve from C to Golang is very low, given the similarities in the language
structure.
3. As it is a compiled language, Golang runs natively on embedded devices.
4. Go is statically linked into a single binary, with no dependencies or libraries required at
the device (note that this is true for applications compiled with CGO_ENABLED=0).
5. Go provides wide platform coverage for cross-compilation to support different
architectures
6. Similar in size with static C binaries, Go binaries continue to get smaller as their compilers
get optimized.
7. Both the client and the backend are written in the same language
Go vs C: size
● gcc main.c
○ 8,5K
● ldd a.out
○ linux-vdso.so.1
○ libc.so.6
○ /lib64/ld-linux-x86-64.so.2
● gcc -static main.c
○ 892K
● gcc -static main.c & strip
○ 821K
package main
func main() {
println("hello world")
}
#include <stdio.h>
int main(void)
{
printf("hello worldn");
return 0;
}● $ go build
○ 938K
● $ go build -ldflags ‘-s -w’
○ 682K
● $ go build & strip
○ 623K
package main
import “fmt”
func main() {
fmt.Println("hello world")
}
● $ go build
○ 1,5M
Go vs C: speed
1. Go is fully garbage-collected
2. Go declaration syntax says nothing about stack and heap allocations making
those implementation dependant ($ go build -gcflags -m; )
3. Fast compilation
4. Go provides support for concurrent execution and communication
5. The speed of developer is most important in most cases and Go really excels
here
https://benchmarksgame-team.pages.debian.net/benchmarksgame/faster/go-gcc.html
Compilation
● Compilers
○ The original gc, the Go compiler, was written in C
○ As of Go 1.5 the compiler is written in Go with a recursive descent parser
and uses a custom loader, based on the Plan 9 loader
○ gccgo (frontend for GCC; https://golang.org/doc/install/gccgo)
■ gcc 7 supports Go 1.8.1
● Compilation
○ fast (large modules compiled within seconds)
○ single binary file (no dependencies, no virtual machines)
■ from Go 1.5 possible to create shared libraries and dynamic linking but
only on x86 architecture
○ makefile
(https://github.com/mendersoftware/mender/blob/master/Makefile)
Cross compilation (https://golang.org/doc/install/source#environment)
$GOOS / $GOARCH amd64 386 arm arm64 ppc64le ppc64 mips64le mips64 mipsle mips
android X
darwin X X X
dragonfly X
freebsd X X X
linux X X X X X X X X X X
netbsd X X X
openbsd X X X
plan9 X X
solaris X
windows X X
Debugging
● Gdb
● Delve (https://github.com/derekparker/delve)
C code inside Go
● CGO (https://golang.org/cmd/cgo/)
○ allows Go to access C library
functions and global variables
○ imported C functions are
available under virtual C
package
○ CGO_ENABLED
○ There is a cost associated with
calling C APIs (~150ns on Xeon
processor)
/*
#cgo LDFLAGS: -lpcap
#include <stdlib.h>
#include <pcap.h>
*/
import "C"
func getDevice() (string, error) {
var errMsg string
cerr := C.CString(errMsg)
defer C.free(unsafe.Pointer(cerr))
cdev := C.pcap_lookupdev(cerr)
dev := C.GoString(cdev)
return dev, nil
}
C++ code inside go
● SWIG
○ Simplified Wrapper and
Interface Generator
○ Used to create wrapper code
to connect C and C++ to other
languages
○ http://www.swig.org/Doc2.0/
Go.html
// helloclass.cpp
std::string HelloClass::hello(){
return "world";
}
// helloclass.h
class HelloClass
{
public:
std::string hello();
}
// mylib.swig
%module mylib
%{
#include "helloclass.h"
%}
Shared Go libraries
● Possible from Go 1.5
○ -buildmode argument
■ archive
■ c-archive
■ c-shared
■ shared
■ exe
● ~ go build -buildmode=shared -o
myshared
● ~ go build -linkshared -o app
myshared
// package name: mygolib
package main
import "C"
import "fmt"
//export SayHiElc
func SayHiElc(name string) {
fmt.Printf("Hello ELC: %s!n", name)
}
func main() {
// We need the main for Go to
// compile C shared library
}
Shared C libraries
● ~ go build -buildmode=c-shared -o
mygolib.a mygolib.go
● ~ gcc -o myapp myapp.c mygolib.a
// mygolib.h
typedef signed char GoInt8;
typedef struct { char *p; GoInt n; }
GoString;
extern void SayHiElc(GoString p0);
// myapp.c
#include "mygolib.h"
#include <stdio.h>
int main() {
printf("Go from C app.n");
GoString name = {"Prague", 6};
SayHiElc(name);
return 0;
}
Embedded Go
● Heap vs stack
○ go build -gcflags -m
○ ./main.go:17: msg escapes to
heap
● Unsafe code
○ C: *(uint8_t*)0x1111 = 0xFF;
○ Manipulating hardware
directly is possible with GO,
but it has been made
intentionally cumbersome.
file, _ := os.OpenFile("/dev/gpiomem",
os.O_RDWR|os.O_SYNC, 0);
mem, _ := syscall.Mmap(int(file.Fd()),
0x20000000, 4096,
syscall.PROT_READ|syscall.PROT_WRITE,
syscall.MAP_SHARED)
header :=
*(*reflect.SliceHeader)(unsafe.Pointer(&mem)
)
memory =
*(*[]uint32)(unsafe.Pointer(&header))
Our experience with Go: cons
1. Messy vendoring of 3rd party libraries
2. Quality of community libraries varies a lot
3. Some issues with Yocto Go layer at the beginning
○ all gone after recent efforts of integrating Go with Yocto
4. While using cgo all the easiness of cross-compiling is gone
Our experience with Go: pros
1. Easy transition from C/Python (took couple of days to be
productive in Go)
2. Very nice tooling and standard library
3. Some tasks exchange between backend and client teams
happened, but we’ve been able to share lot of tools (CI, code
coverage)
4. We can share some code between the client and the backend
5. Really productive language (especially when developing some kind
of network communication)
6. Forced coding standard so all the code looks the same and is easy
to read
Demo
● ThermoStat ™
○ https://github.com/mendersoftware/thermostat
Q&A

More Related Content

What's hot

The Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventureThe Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventuremylittleadventure
 
Coding with golang
Coding with golangCoding with golang
Coding with golangHannahMoss14
 
Go Programming Language by Google
Go Programming Language by GoogleGo Programming Language by Google
Go Programming Language by GoogleUttam Gandhi
 
Golang from Scala developer’s perspective
Golang from Scala developer’s perspectiveGolang from Scala developer’s perspective
Golang from Scala developer’s perspectiveSveta Bozhko
 
Wonders of Golang
Wonders of GolangWonders of Golang
Wonders of GolangKartik Sura
 
Building Command Line Tools with Golang
Building Command Line Tools with GolangBuilding Command Line Tools with Golang
Building Command Line Tools with GolangTakaaki Mizuno
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go langAmal Mohan N
 
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019corehard_by
 
Vendoring - Go west 2018-03-07
Vendoring - Go west 2018-03-07Vendoring - Go west 2018-03-07
Vendoring - Go west 2018-03-07Max Ekman
 
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...corehard_by
 
Web technology slideshare
Web technology slideshareWeb technology slideshare
Web technology slideshareGuruAbirami2
 
An introduction to go programming language
An introduction to go programming languageAn introduction to go programming language
An introduction to go programming languageTechnology Parser
 
ATO 2014 - So You Think You Know 'Go'? The Go Programming Language
ATO 2014 - So You Think You Know 'Go'? The Go Programming LanguageATO 2014 - So You Think You Know 'Go'? The Go Programming Language
ATO 2014 - So You Think You Know 'Go'? The Go Programming LanguageJohn Potocny
 
[INNOVATUBE] Tech Talk #3: Golang - Vũ Nguyễn
[INNOVATUBE] Tech Talk #3: Golang - Vũ Nguyễn [INNOVATUBE] Tech Talk #3: Golang - Vũ Nguyễn
[INNOVATUBE] Tech Talk #3: Golang - Vũ Nguyễn Nexus FrontierTech
 
[INNOVATUBE] Tech Talk #3: Golang - Takaaki Mizuno
 [INNOVATUBE] Tech Talk #3: Golang - Takaaki Mizuno [INNOVATUBE] Tech Talk #3: Golang - Takaaki Mizuno
[INNOVATUBE] Tech Talk #3: Golang - Takaaki MizunoNexus FrontierTech
 

What's hot (20)

The Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventureThe Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventure
 
Coding with golang
Coding with golangCoding with golang
Coding with golang
 
Go Programming Language by Google
Go Programming Language by GoogleGo Programming Language by Google
Go Programming Language by Google
 
Golang from Scala developer’s perspective
Golang from Scala developer’s perspectiveGolang from Scala developer’s perspective
Golang from Scala developer’s perspective
 
Wonders of Golang
Wonders of GolangWonders of Golang
Wonders of Golang
 
Go Lang
Go LangGo Lang
Go Lang
 
An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
 
Building Command Line Tools with Golang
Building Command Line Tools with GolangBuilding Command Line Tools with Golang
Building Command Line Tools with Golang
 
Golang
GolangGolang
Golang
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go lang
 
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
 
GoLang Introduction
GoLang IntroductionGoLang Introduction
GoLang Introduction
 
Vendoring - Go west 2018-03-07
Vendoring - Go west 2018-03-07Vendoring - Go west 2018-03-07
Vendoring - Go west 2018-03-07
 
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
 
Introduction to Go-Lang
Introduction to Go-LangIntroduction to Go-Lang
Introduction to Go-Lang
 
Web technology slideshare
Web technology slideshareWeb technology slideshare
Web technology slideshare
 
An introduction to go programming language
An introduction to go programming languageAn introduction to go programming language
An introduction to go programming language
 
ATO 2014 - So You Think You Know 'Go'? The Go Programming Language
ATO 2014 - So You Think You Know 'Go'? The Go Programming LanguageATO 2014 - So You Think You Know 'Go'? The Go Programming Language
ATO 2014 - So You Think You Know 'Go'? The Go Programming Language
 
[INNOVATUBE] Tech Talk #3: Golang - Vũ Nguyễn
[INNOVATUBE] Tech Talk #3: Golang - Vũ Nguyễn [INNOVATUBE] Tech Talk #3: Golang - Vũ Nguyễn
[INNOVATUBE] Tech Talk #3: Golang - Vũ Nguyễn
 
[INNOVATUBE] Tech Talk #3: Golang - Takaaki Mizuno
 [INNOVATUBE] Tech Talk #3: Golang - Takaaki Mizuno [INNOVATUBE] Tech Talk #3: Golang - Takaaki Mizuno
[INNOVATUBE] Tech Talk #3: Golang - Takaaki Mizuno
 

Similar to Comparing C and Go

Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io
 
Golang : A Hype or the Future?
Golang : A Hype or the Future?Golang : A Hype or the Future?
Golang : A Hype or the Future?Mindfire LLC
 
Go for Mobile Games
Go for Mobile GamesGo for Mobile Games
Go for Mobile GamesTakuya Ueda
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to GoSimon Hewitt
 
Mobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse BindingMobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse BindingTakuya Ueda
 
Advantages of golang development services &amp; 10 most used go frameworks
Advantages of golang development services &amp; 10 most used go frameworksAdvantages of golang development services &amp; 10 most used go frameworks
Advantages of golang development services &amp; 10 most used go frameworksKaty Slemon
 
Develop Android app using Golang
Develop Android app using GolangDevelop Android app using Golang
Develop Android app using GolangSeongJae Park
 
Scaling applications with go
Scaling applications with goScaling applications with go
Scaling applications with goVimlesh Sharma
 
Introduction to Application Development in Python and Gtk+ / Hildon @ Maemo 5
Introduction to Application Development in Python and Gtk+ / Hildon @ Maemo 5Introduction to Application Development in Python and Gtk+ / Hildon @ Maemo 5
Introduction to Application Development in Python and Gtk+ / Hildon @ Maemo 5Amanda Lam
 
Golang execution modes
Golang execution modesGolang execution modes
Golang execution modesTing-Li Chou
 
Designing flexible apps deployable to App Engine, Cloud Functions, or Cloud Run
Designing flexible apps deployable to App Engine, Cloud Functions, or Cloud RunDesigning flexible apps deployable to App Engine, Cloud Functions, or Cloud Run
Designing flexible apps deployable to App Engine, Cloud Functions, or Cloud Runwesley chun
 
Gomobile: gophers in the land of Android
Gomobile: gophers in the land of AndroidGomobile: gophers in the land of Android
Gomobile: gophers in the land of AndroidJovica Popovic
 
Getting started with go - Florin Patan - Codemotion Milan 2016
Getting started with go - Florin Patan - Codemotion Milan 2016Getting started with go - Florin Patan - Codemotion Milan 2016
Getting started with go - Florin Patan - Codemotion Milan 2016Codemotion
 
Cape Cod Web Technology Meetup - 3
Cape Cod Web Technology Meetup - 3Cape Cod Web Technology Meetup - 3
Cape Cod Web Technology Meetup - 3Asher Martin
 
OVERVIEW: Chromium Source Tree
OVERVIEW: Chromium Source TreeOVERVIEW: Chromium Source Tree
OVERVIEW: Chromium Source TreeChang W. Doh
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about goDvir Volk
 

Similar to Comparing C and Go (20)

Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and Golang
 
Golang : A Hype or the Future?
Golang : A Hype or the Future?Golang : A Hype or the Future?
Golang : A Hype or the Future?
 
Go for Mobile Games
Go for Mobile GamesGo for Mobile Games
Go for Mobile Games
 
Go, meet Lua
Go, meet LuaGo, meet Lua
Go, meet Lua
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
 
Mobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse BindingMobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse Binding
 
Advantages of golang development services &amp; 10 most used go frameworks
Advantages of golang development services &amp; 10 most used go frameworksAdvantages of golang development services &amp; 10 most used go frameworks
Advantages of golang development services &amp; 10 most used go frameworks
 
Develop Android app using Golang
Develop Android app using GolangDevelop Android app using Golang
Develop Android app using Golang
 
G++ & GCC
G++ & GCCG++ & GCC
G++ & GCC
 
Why Go Lang?
Why Go Lang?Why Go Lang?
Why Go Lang?
 
Scaling applications with go
Scaling applications with goScaling applications with go
Scaling applications with go
 
Introduction to Application Development in Python and Gtk+ / Hildon @ Maemo 5
Introduction to Application Development in Python and Gtk+ / Hildon @ Maemo 5Introduction to Application Development in Python and Gtk+ / Hildon @ Maemo 5
Introduction to Application Development in Python and Gtk+ / Hildon @ Maemo 5
 
Golang execution modes
Golang execution modesGolang execution modes
Golang execution modes
 
Designing flexible apps deployable to App Engine, Cloud Functions, or Cloud Run
Designing flexible apps deployable to App Engine, Cloud Functions, or Cloud RunDesigning flexible apps deployable to App Engine, Cloud Functions, or Cloud Run
Designing flexible apps deployable to App Engine, Cloud Functions, or Cloud Run
 
Gomobile: gophers in the land of Android
Gomobile: gophers in the land of AndroidGomobile: gophers in the land of Android
Gomobile: gophers in the land of Android
 
Getting started with go - Florin Patan - Codemotion Milan 2016
Getting started with go - Florin Patan - Codemotion Milan 2016Getting started with go - Florin Patan - Codemotion Milan 2016
Getting started with go - Florin Patan - Codemotion Milan 2016
 
Cape Cod Web Technology Meetup - 3
Cape Cod Web Technology Meetup - 3Cape Cod Web Technology Meetup - 3
Cape Cod Web Technology Meetup - 3
 
Golang introduction
Golang introductionGolang introduction
Golang introduction
 
OVERVIEW: Chromium Source Tree
OVERVIEW: Chromium Source TreeOVERVIEW: Chromium Source Tree
OVERVIEW: Chromium Source Tree
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 

Recently uploaded

main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxPurva Nikam
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 

Recently uploaded (20)

main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptx
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 

Comparing C and Go

  • 1. Marcin Pasinski Mender.io Develop your Embedded Applications Faster: Comparing C and Golang
  • 2. My view on C vs Go ● I think Go is great and very productive programming language ● It excels when developing networking code ● I’m not considering it a replacement or competitor for C ● Among the other things garbage collection alone ensures that
  • 3. Who am I? ● Marcin Pasinski ○ 10+ years in software development ○ M. Sc., Electronics and Telecommunication ○ marcin.pasinski@northern.tech ■ OTA updater for Linux devices ■ Integrated with Yocto ■ Open source (Apache v2 license) ■ Written in Go ■ Configuration management tool ■ Open source (GPL v3 license) ■ Written in C
  • 4. Agenda ● Why did we choose go ● Go basics for Embedded development ● Code samples ● Demo
  • 5. Language requirements 1. “External impact” ○ Size requirements on device ○ Setup requirement in Yocto Project ○ Possibility to compile for multiple platforms 2. “Internal considerations” ○ Competences in the company ○ Code share/reuse ○ Development speed ○ Access to common libraries (JSON, SSL, HTTP) ○ “Automatic memory management” ○ “Security enablers” (buffer overflow protection, etc.)
  • 6. Language comparison C C++ Go Size requirements in devices Lowest Low (1.8MB more) Low (2.1 MB more, however will increase with more binaries) Setup requirements in Yocto None None Requires 1 layer (golang)* Competence in the company Good Have some long time users Only couple of people know it Buffer under/overflow protection None Little Yes Code reuse/sharing from CFEngine Good Easy (full backwards compatibility) Can import C API Automatic memory management No Available, but not enforced Yes Standard data containers No Yes Yes JSON json-c jsoncpp Built-in HTTP library curl curl Built-in SSL OpenSSL OpenSSL Built-in * Go is natively supported by Yocto Project from Pyro release (Yocto 2.3)
  • 7. Yocto build comparison C C++ C++/Qt Go ... Pure image size 8.4MB 10.2MB 20.8MB* 14.6MB Size with network stack 13.4MB (curl) 15.2MB (curl) 20.8MB* 14.6MB Shared dependencies Yes Yes Yes No/Maybe Extra Yocto layer needed No No Yes Yes** Deployment complexity Binary Binary Binary + Qt Binary * Required some changes to upstream Yocto layer ** Go is natively supported by Yocto from Pyro release (Yocto 2.3)
  • 8. Why did we pick up Go? 1. Golang has lots of core language features and libraries that allows much faster development of applications. 2. The learning curve from C to Golang is very low, given the similarities in the language structure. 3. As it is a compiled language, Golang runs natively on embedded devices. 4. Go is statically linked into a single binary, with no dependencies or libraries required at the device (note that this is true for applications compiled with CGO_ENABLED=0). 5. Go provides wide platform coverage for cross-compilation to support different architectures 6. Similar in size with static C binaries, Go binaries continue to get smaller as their compilers get optimized. 7. Both the client and the backend are written in the same language
  • 9. Go vs C: size ● gcc main.c ○ 8,5K ● ldd a.out ○ linux-vdso.so.1 ○ libc.so.6 ○ /lib64/ld-linux-x86-64.so.2 ● gcc -static main.c ○ 892K ● gcc -static main.c & strip ○ 821K package main func main() { println("hello world") } #include <stdio.h> int main(void) { printf("hello worldn"); return 0; }● $ go build ○ 938K ● $ go build -ldflags ‘-s -w’ ○ 682K ● $ go build & strip ○ 623K package main import “fmt” func main() { fmt.Println("hello world") } ● $ go build ○ 1,5M
  • 10. Go vs C: speed 1. Go is fully garbage-collected 2. Go declaration syntax says nothing about stack and heap allocations making those implementation dependant ($ go build -gcflags -m; ) 3. Fast compilation 4. Go provides support for concurrent execution and communication 5. The speed of developer is most important in most cases and Go really excels here https://benchmarksgame-team.pages.debian.net/benchmarksgame/faster/go-gcc.html
  • 11. Compilation ● Compilers ○ The original gc, the Go compiler, was written in C ○ As of Go 1.5 the compiler is written in Go with a recursive descent parser and uses a custom loader, based on the Plan 9 loader ○ gccgo (frontend for GCC; https://golang.org/doc/install/gccgo) ■ gcc 7 supports Go 1.8.1 ● Compilation ○ fast (large modules compiled within seconds) ○ single binary file (no dependencies, no virtual machines) ■ from Go 1.5 possible to create shared libraries and dynamic linking but only on x86 architecture ○ makefile (https://github.com/mendersoftware/mender/blob/master/Makefile)
  • 12. Cross compilation (https://golang.org/doc/install/source#environment) $GOOS / $GOARCH amd64 386 arm arm64 ppc64le ppc64 mips64le mips64 mipsle mips android X darwin X X X dragonfly X freebsd X X X linux X X X X X X X X X X netbsd X X X openbsd X X X plan9 X X solaris X windows X X
  • 13. Debugging ● Gdb ● Delve (https://github.com/derekparker/delve)
  • 14. C code inside Go ● CGO (https://golang.org/cmd/cgo/) ○ allows Go to access C library functions and global variables ○ imported C functions are available under virtual C package ○ CGO_ENABLED ○ There is a cost associated with calling C APIs (~150ns on Xeon processor) /* #cgo LDFLAGS: -lpcap #include <stdlib.h> #include <pcap.h> */ import "C" func getDevice() (string, error) { var errMsg string cerr := C.CString(errMsg) defer C.free(unsafe.Pointer(cerr)) cdev := C.pcap_lookupdev(cerr) dev := C.GoString(cdev) return dev, nil }
  • 15. C++ code inside go ● SWIG ○ Simplified Wrapper and Interface Generator ○ Used to create wrapper code to connect C and C++ to other languages ○ http://www.swig.org/Doc2.0/ Go.html // helloclass.cpp std::string HelloClass::hello(){ return "world"; } // helloclass.h class HelloClass { public: std::string hello(); } // mylib.swig %module mylib %{ #include "helloclass.h" %}
  • 16. Shared Go libraries ● Possible from Go 1.5 ○ -buildmode argument ■ archive ■ c-archive ■ c-shared ■ shared ■ exe ● ~ go build -buildmode=shared -o myshared ● ~ go build -linkshared -o app myshared // package name: mygolib package main import "C" import "fmt" //export SayHiElc func SayHiElc(name string) { fmt.Printf("Hello ELC: %s!n", name) } func main() { // We need the main for Go to // compile C shared library }
  • 17. Shared C libraries ● ~ go build -buildmode=c-shared -o mygolib.a mygolib.go ● ~ gcc -o myapp myapp.c mygolib.a // mygolib.h typedef signed char GoInt8; typedef struct { char *p; GoInt n; } GoString; extern void SayHiElc(GoString p0); // myapp.c #include "mygolib.h" #include <stdio.h> int main() { printf("Go from C app.n"); GoString name = {"Prague", 6}; SayHiElc(name); return 0; }
  • 18. Embedded Go ● Heap vs stack ○ go build -gcflags -m ○ ./main.go:17: msg escapes to heap ● Unsafe code ○ C: *(uint8_t*)0x1111 = 0xFF; ○ Manipulating hardware directly is possible with GO, but it has been made intentionally cumbersome. file, _ := os.OpenFile("/dev/gpiomem", os.O_RDWR|os.O_SYNC, 0); mem, _ := syscall.Mmap(int(file.Fd()), 0x20000000, 4096, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED) header := *(*reflect.SliceHeader)(unsafe.Pointer(&mem) ) memory = *(*[]uint32)(unsafe.Pointer(&header))
  • 19. Our experience with Go: cons 1. Messy vendoring of 3rd party libraries 2. Quality of community libraries varies a lot 3. Some issues with Yocto Go layer at the beginning ○ all gone after recent efforts of integrating Go with Yocto 4. While using cgo all the easiness of cross-compiling is gone
  • 20. Our experience with Go: pros 1. Easy transition from C/Python (took couple of days to be productive in Go) 2. Very nice tooling and standard library 3. Some tasks exchange between backend and client teams happened, but we’ve been able to share lot of tools (CI, code coverage) 4. We can share some code between the client and the backend 5. Really productive language (especially when developing some kind of network communication) 6. Forced coding standard so all the code looks the same and is easy to read
  • 21. Demo ● ThermoStat ™ ○ https://github.com/mendersoftware/thermostat
  • 22. Q&A