Go language is compatible with c language; Go language can call C language and can also call C language. There is a Cgo command in the Go language toolkit, which is used to handle operations related to Go calling C; and Go functions can be exported to C, just add "//export funcname" in front of the function to be exported, and then you can Use the "go build -buildmode=c-shared -o libxxx.so" command to compile and generate dynamic libraries and header files for use in C language.

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
C language and golang are compatible. The .c file you write in C can be referenced by golang and used directly.
Many of the various modern high-level programming languages are built on top of the C language. Basically, they can call the C language, and this is also required and exists in some cases. meaning. The Go language supports this aspect very well. It can not only call the C language, but also the C language. This article will explain the relevant content.
Basic description
There is a Cgo command in the Go language toolkit, which is used to handle operations related to Go calling C. We can use this command directly or call it automatically when running or building a Go program.
Cgo’s processing of C language itself relies on the C language-related compilation tool chain in the system, so you need to pay attention to the settings, mainly the Go environment variable settings:

Special attention should be paid to the fact that Cgo needs to be enabled, which can be set using the go env -w CGO_ENABLED=1 command. In the picture above, you can see some FLAGS parameters during C compilation. If necessary, you can adjust the settings accordingly. In addition, the above CC CXX is the setting of the compilation tool chain, which can also be adjusted according to the needs.
Calling C in Go
Calling C language in Go will eventually be displayed as a pseudo package named C in Go , In Go, use the comment #include ... above the import "C" line to reference C language-related libraries. The public variables and functions in these referenced libraries will be hung into the C package for use in Go. The following is a simple demonstration:

To call C in Go, just do the above, and it is very convenient to use.
Generally speaking, C language program projects may include assembly code in addition to C language code; or the project may also be C/C mixed programming. These projects can be used in Go, and Cgo will automatically recognize the suffix as .c .s .S .sx . cc .cpp .cxx file, and call the corresponding compiler to compile.
It should be noted that syntax not supported by C such as overloading and class methods in C needs to be wrapped with a layer of C language standard functions if you want to use it in Go. The usage method is the same as calling C in C language. Same. [Related recommendations: Go video tutorial, Programming teaching]
Calling Go in C
If there are any problems in the following test, you can try go clean and reset the project before proceeding.
Go functions can be exported to C. Just add //export funcname in front of the function to be exported, and then use go build -buildmode =c-shared -o libxxx.so The command compiles and generates dynamic libraries and header files for use in C language:


Also you can Use go build -buildmode=c-archive -o libxxx.a to compile and generate a static library that can be used in C language.
Differences in data types
The call between the two languages is actually the transfer processing of data. It should be noted that the two are not the same after all. Language, so there are restrictions on the data types that can be interacted between the two. Sometimes there is a need to force data type conversion, such as the following code:
package rand
// #include <stdlib.h>
import "C"
func Random() int {
return int(C.random()) // C函数返回值给Go,random的返回值是long类型
}
func Seed(i int) {
C.srandom(C.uint(i)) // Go传值给C的函数,srandom函数接收uint类型数据
}The basic numerical type conversions available between the two are as follows:
C.char, C.schar (signed char), C.uchar (unsigned char) C.short, C.ushort (unsigned short) C.int, C.uint (unsigned int) C.long, C.ulong (unsigned long) C.longlong (long long), C.ulonglong (unsigned long long) C.float, C.double C.complexfloat (complex float), C.complexdouble (complex double)
In addition to the above basic types, Pointers can also be passed around. In particular, the void* pointer in C language is equivalent to the unsafe.Pointer in Go.
__int128_t and __uint128_t in C are equivalent to [16]byte in Go.
C中函数传输参数为数组的话直接传递数组名就行,在Go中向这类函数传递数组需要传递数组第一个元素的地址,另外需要注意的是数组中元素也必须是C语言中支持的类型:
C.f(&C.arr[0])
C中并没有string类型,使用字符串时需要进行处理:
package print
// #include <stdio.h>
// #include <stdlib.h>
import "C"
import "unsafe"
func Print(s string) {
cs := C.CString(s) // 这个方式会将字符串拷贝一份,返回指针,注意使用完需要释放内存
defer C.free(unsafe.Pointer(cs)) // defer修饰的语句会在该函数退出前执行
C.fputs(cs, (*C.FILE)(C.stdout))
}另外C语言的字符串 *C.char 可以使用 C.GoString() 转换成Go中的字符串。
C中的 struct union enum 这些类型在Go使用需要加上对应的前缀,变成 struct_xxx union_xxx enum_xxx 。其中联合体在Go中将成为字节数组的形式。这些对象的成员名如果和Go的关键词一样的话,在Go中使用需要在成员名前面加下划线,比如 x._name 。
C中的 sizeof 在Go中需要使用 C.sizeof_T 方式使用,T是变量数据类型。
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of Is go language compatible with c language?. For more information, please follow other related articles on the PHP Chinese website!
The Performance Race: Golang vs. CApr 16, 2025 am 12:07 AMGolang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.
Golang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AMGolang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.
Golang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AMGoimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:
C and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AMC is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.
Golang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AMGolang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.
Golang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AMThe core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.
Golang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PMGo language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.
Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PMConfused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.






