A programming language with many features can make it quite complicated. This can take a lot of time to figure out which features will provide the optimal solution to a query.
In contrast, the Go language is enjoyable to write and easy to work on and maintain. This trade-off has made Go unique amongst the other programming languages, as the language is fixed. It doesn't have most of the features of other programming languages and has no intention of adding them. The reason is that it would make Go bigger and more complex, not better. Then again, there might be certain instances where the need for specific features is in demand, but Go fails to provide them in this regard. Therefore, Go can call code written in C.
We can use C within the Go language when there is a need for certain functionalities that are not available within Go, and this can be quite a predicament. Therefore C comes into play, as code written in C can be executed successfully within a Go file. As a result, all the benefits of C are available within Go.
Let's look at the code below:
package main// #include "sum.h"import "C"import "fmt"func main(){num_1:=10num_2:=5sum := C.calc_sum(C.int(num_1),C.int(num_2))fmt.Printf("%d + %d = %d\n", num_1,num_2,sum)}
The header file, sum.h
, contains the declaration of the function that will calculate the sum.
The C file, sum.c
, includes the implementation of the function that will calculate the sum.
In the Go file, main.go
:
Line 1: We declare this go file as a part of the main package.
Line 2: This is the C code, and the important thing to note here is that this is written as comments in the Go file just before import "C"
.
Line 3: The import "C"
tells that we use C in Go.
Line 4: We import the fmt
library, which allows us to format strings.
Line 6: We declare the main function.
Lines 7–8: We declare two variables.
Line 9: The calc_sum()
declared in the sum.h
file is called, and the two variables are typecast to C integer type, and it returns the result, which is stored in the sum
variable.
Line 10: We display the results to the console.
Free Resources