All Resources
GuideAutomation2026-03-06
G-Code Basics for Software Developers
A developer-oriented guide to CNC G-code. Learn the coordinate system, common commands (G0, G1, G2, G3), feed rates, spindle control, and how to generate toolpaths programmatically.
What Is G-Code?
G-code is the programming language for CNC (Computer Numerical Control) machines — mills, lathes, routers, plasma cutters, and 3D printers. Each line of G-code is an instruction: move here, cut at this speed, turn the spindle on.
If you're building manufacturing software, you'll eventually need to generate, parse, or validate G-code. This guide covers the fundamentals.
Coordinate System
CNC machines use a Cartesian coordinate system:
- X, Y — horizontal plane (left-right, front-back)
- Z — vertical axis (up-down, or depth for a router)
- G90 — absolute positioning (coordinates relative to machine origin)
- G91 — incremental positioning (coordinates relative to current position)
Essential Commands
Motion Commands
- G0 X_ Y_ Z_ — Rapid move (fastest speed, no cutting). Used for positioning.
- G1 X_ Y_ Z_ F_ — Linear cut at feed rate F. The workhorse command.
- G2 X_ Y_ I_ J_ F_ — Clockwise arc. I,J are the arc center offset from the start point.
- G3 X_ Y_ I_ J_ F_ — Counter-clockwise arc.
Spindle & Tool
- M3 S12000 — Spindle on clockwise at 12000 RPM
- M5 — Spindle off
- T1 M6 — Select tool 1 and perform tool change
Program Control
- M0 — Program pause (operator must press cycle start to continue)
- M30 — Program end and rewind
A Simple Program
G90 G21 (Absolute mode, millimeters)
T1 M6 (Select tool 1)
M3 S10000 (Spindle on at 10000 RPM)
G0 X0 Y0 Z5 (Rapid to start position)
G1 Z-2 F200 (Plunge cut to -2mm at 200mm/min)
G1 X50 F800 (Cut along X to 50mm)
G1 Y30 (Cut along Y to 30mm)
G1 X0 (Cut back to X0)
G1 Y0 (Cut back to Y0)
G0 Z5 (Retract)
M5 (Spindle off)
M30 (Program end)This cuts a 50mm x 30mm rectangle at 2mm depth.
Generating G-Code Programmatically
When building a G-code generator in C# or Python:
- Define your toolpath as a sequence of points and arc segments
- Apply feed rates based on material, tool, and operation type
- Add safe retract moves (Z clearance) between operations
- Format output — G-code is plain text, one command per line
- Validate — check for rapid moves into the workpiece, out-of-bounds coordinates, and missing feed rates
Tips for Developers
- G-code is case-insensitive, but conventionally uppercase
- Comments use parentheses: (this is a comment)
- Feed rate (F) is modal — it stays active until changed
- Always start with G90 (absolute) and G21 (metric) or G20 (imperial) to establish the coordinate mode
- Test generated G-code in a simulator (e.g., NCViewer.com) before running on a real machine
CNCG-CodeManufacturingTutorial