cgo is written in "comments" in go which means by default it's given comment syntax highlighting. It would be nice have proper golang and C syntax highlighting but within cgo files.
package main
// ... C code or #include here ...
import "C"
... Go code here ...
I'd like this for either Visual Studio Code, or ViM.
How can this be achieved?
I woul say that, depending on your editor this is somewhere between impossible, and pointlessly difficult.
The only way you can tell the difference between a normal comment block and one used by cgo, is that the cgo block is immediately followed by import "C"
. Depending on how the syntax highlighting lexer for your editor is constructed it may or may not be able to detect this.
A possible partial solution would be to write a simplified subset of the C highlighter that only effects obvious code, then apply that to all comment blocks. Not a very good solution, but better than nothing.
Good luck!
One way is to place the C code in a header file, for instance example.h
, then in your Go program use:
// #include "example.h"
import "C"
When opening example.h
, you get syntax highlighting.
Alternatively, for ViM, this plugin can supposedly be able to highlight C code that is part of Go code, but it might not be straightforward to configure: SyntaxRange