← All guides
CNC drilling operation

G-Code Explained: How CNC Programming Works

Tutorials

G-Code Explained: How CNC Programming Works

G-code is the language that controls CNC machines. Every line tells the machine one thing to do — move to a position, start the spindle, or change a tool. The machine reads these instructions one by one from top to bottom and executes them in order.

There is nothing magical about G-code. It is a list of coordinates and commands that has been the standard for machine tools since the 1950s. The same language that runs a $500 hobby router also runs a $500,000 five-axis machining center.

This guide explains how G-code works at a fundamental level, starting from the simplest possible concepts: the structure of a command, how the machine interprets coordinates, modal behavior, and how to read any CNC program with confidence.


The Structure of a G-Code Line

Every G-code command follows the same basic structure:

N10 G01 X100 Y50 Z-5 F200 S3000 M08

Breaking it down from left to right:

Part Value What It Does
Line number N10 Optional label for reference
Preparatory command G01 Selects the operation type
X coordinate X100 Target position on X axis
Y coordinate Y50 Target position on Y axis
Z coordinate Z-5 Target position on Z axis
Feed rate F200 Cutting speed in mm/min
Spindle speed S3000 RPM of the cutting tool
Miscellaneous command M08 Auxiliary machine function

Not every line needs all of these parts. Many values are modal — once set they remain active until you change them. If you set F200 on line 10 every following line uses F200 until you write a different F-word.

The Three Types of Words

G-code commands are built from three types of words:

G-words (Preparatory functions) control the type of operation:

Code Meaning
G00 Rapid positioning (fast move, not cutting)
G01 Linear interpolation (straight cut)
G02 Circular interpolation clockwise (arc)
G03 Circular interpolation counterclockwise
G81 Drilling cycle
G90 Absolute positioning mode
G91 Incremental positioning mode

M-words (Miscellaneous functions) control the machine itself:

Code Meaning
M03 Spindle on clockwise
M05 Spindle stop
M06 Tool change
M08 Coolant on
M09 Coolant off
M30 End program and rewind

Address words (X, Y, Z, F, S, etc.) provide the values:

Word Controls Example
X, Y, Z Axis positions X100 Y50 Z-5
F Feed rate F200 (mm/min)
S Spindle speed S3000 (RPM)
T Tool number T1, T2, T3
H Tool offset number H1, H2
D Cutter compensation number D1
I, J, K Arc center offsets I25 J0

How the Machine Reads a Program

A CNC machine reads a program sequentially — line by line from top to bottom. It does not skip lines, interpret intent, or guess what you meant. It follows the instructions exactly as written.

; The machine reads this program in this order:
G90 G94 G17 G54   ; Line 1: Set modes
G21               ; Line 2: Set units to mm
M06 T1            ; Line 3: Change to tool 1
M03 S3000         ; Line 4: Start spindle
G00 X0 Y0 Z5      ; Line 5: Rapid to start position
G01 Z-2 F100      ; Line 6: Feed into material
G01 X100 F300     ; Line 7: Cut to X100
G00 Z5            ; Line 8: Rapid retract
M05               ; Line 9: Stop spindle
M30               ; Line 10: End program

The machine processes line 1 first, then line 2, and so on until it reaches M30 which tells it the program is complete. At M30 the controller stops the machine, turns off the spindle and coolant if still running, and rewinds the program to the beginning. The machine is now in the same state it was before the program started, ready to run again with a new workpiece.

How Fast Does the Machine Read?

CNC controllers read ahead by several lines. While the machine is executing line 5 the controller is already reading lines 6 through 10 and preparing the motion calculations. This look-ahead feature allows the machine to maintain smooth motion at high speeds.

The number of lines the controller can look ahead depends on the specific hardware and firmware. Industrial Fanuc controllers may read ahead 200 to 1000 lines allowing them to maintain high speeds even on complex toolpaths with many small direction changes. GRBL running on an Arduino reads ahead about 20 lines. This is enough for simple toolpaths but causes stuttering on complex 3D contours with many short line segments. This is why GRBL machines may slow down on complex code with many short segments — the controller runs out of look-ahead data and has to wait for the next line.


Understanding the difference between modal and one-shot commands is essential for reading and writing G-code correctly.

Modal commands stay active until they are changed by another command in the same group. You write them once and they affect every following line.

G90 G01 X50 F200  ; G90 and G01 are modal — now active
X100               ; Still in G90 + G01 mode → absolute move to X100
Y50                ; Still in G90 + G01 → absolute move to Y50
X0                 ; Still active → absolute move to X0

The G01 linear interpolation command is in the motion group (group 01). Once activated every subsequent move is a linear feed move until you select G00, G02, or G03 from the same group.

The modal groups are:

Group Codes What It Controls
01 G00, G01, G02, G03, G04 Motion type
02 G17, G18, G19 Work plane
03 G90, G91 Distance mode
05 G94, G95 Feed rate mode
06 G20, G21 Units
07 G40, G41, G42 Cutter compensation
08 G43, G44, G49 Tool length offset
09 G73, G81, G83, G84, G85, G80 Canned cycles
12 G54, G55, G56, G57, G58, G59 Work offset

You can only have one active code from each group at a time. Selecting G02 automatically cancels G01. Selecting G91 automatically cancels G90.

One-Shot Commands

One-shot commands affect only the line they are on. They do not carry over to subsequent lines.

G04 P1000          ; Dwell for 1 second — only this line
G81 R2 Z-10 F150   ; Drilling cycle — cancels after G80
G09 G01 X100       ; Exact stop check — only this line

The most important one-shot command group is the canned cycles (G81 through G89). These special sequences automate drilling tapping and boring operations. Each one runs on a single line but performs multiple machine actions internally: rapid to position, feed to depth, retract, and repeat at the next hole location.


How Coordinates Work in G-Code

Every CNC machine uses a coordinate system based on the three axes. Positions can be specified in two ways.

Absolute Coordinates (G90)

In absolute mode every coordinate is measured from the part zero point (work offset position).

G90 G01 X50 F200   ; Move TO X=50 relative to part zero
G01 X100           ; Move TO X=100 relative to part zero
G01 X25            ; Move TO X=25 relative to part zero

The tool goes to X=50, then X=100, then back to X=25. Each position is calculated from the same fixed reference point.

Incremental Coordinates (G91)

In incremental mode every coordinate is measured from the current tool position.

G91 G01 X50 F200   ; Move +50mm from current position
G01 X50            ; Move another +50mm from there
G01 X50            ; Move another +50mm from there

The total distance moved is 150mm but each line only specifies 50mm. The actual position at the end depends on where the tool started.

The Machine Coordinate System (G53)

The G53 command temporarily overrides the work offset and uses the machine’s built-in coordinate system. This is useful for moves that must go to a fixed machine position regardless of where the part zero is set.

G53 G00 Z0         ; Move Z to machine home position
G53 G00 X0 Y0      ; Move X and Y to machine home

G53 is not modal. It only affects the line it is on. You must repeat G53 on every move that should use machine coordinates instead of work offset coordinates.


How the Controller Processes a Line

When a CNC controller reads a line of G-code it goes through this sequence:

  1. Parse the line into individual words (G01, X100, F200, etc.)
  2. Validate each word — does the command exist? Is the value in range?
  3. Check modal state — what is the current active motion mode? Distance mode? Unit mode?
  4. Plan the move — calculate the acceleration and deceleration needed
  5. Execute — send the motion commands to the drive system

If the controller encounters an error at step 2 it stops the machine immediately and displays an alarm message on the screen. You must acknowledge the alarm, correct the G-code, and restart the program from the beginning. This is why testing new programs in single-block mode is a good practice — you catch errors one line at a time instead of discovering them after the machine has already stopped. Common alarms include unrecognized G-codes, missing required values, and moves that would exceed the machine’s travel limits.

What Happens on an Error

When a controller detects an error it stops the machine immediately. The tool stops where it is and the spindle stops. The controller displays an error message on the screen. You must clear the error correct the G-code and restart the program from the beginning.

This is why simulation is important. A G-code error on a real machine means lost time and potentially a scrapped part. The same error in a simulator is just a message on your computer screen.


Reading G-Code: A Practical Example

Here is a complete program with line-by-line explanations:

%
O1000 (FACE AND DRILL)
; === SETUP ===
N10 G90 G94 G17 G54  ; Absolute positioning, feed/min, XY plane, offset 1
N20 G21              ; Millimeters
; === TOOL 1: FACE MILL ===
N30 M06 T1           ; Load 20mm face mill
N40 M03 S4000        ; Spindle on at 4000 RPM
N50 G00 X-10 Y-10 Z5 ; Rapid to start position above part
N60 G01 Z0 F200      ; Feed to surface
N70 G01 X110 F600    ; Face cut across the part
N80 G00 Y10          ; Rapid to next pass
N90 G01 Z0           ; Feed back to surface
N100 G01 X-10 F600   ; Face cut back
N110 G00 Z50         ; Rapid retract
N120 M05             ; Spindle off
; === TOOL 2: DRILL ===
N130 M06 T2          ; Load 10mm drill
N140 M03 S2500       ; Spindle on at 2500 RPM
N150 G00 X20 Y20 Z10 ; Rapid to first hole position
N160 G81 R2 Z-15 F150 ; Drill hole 1 (20mm deep)
N170 X80             ; Drill hole 2 (at X80 Y20)
N180 Y80             ; Drill hole 3 (at X80 Y80)
N190 X20             ; Drill hole 4 (at X20 Y80)
N200 G80             ; Cancel drill cycle
N210 G00 Z50         ; Retract
N220 M05             ; Spindle off
N230 M30             ; End program
%

Key observations about this program:

  • G90 and G21 are set once at the top and stay active for the whole program
  • G81 is a modal canned cycle but G80 cancels it on line 200
  • Each tool change (M06) stops the machine for the operator to load the tool
  • F and S values are set per tool because each tool needs different speeds

Common Questions About G-Code

Is G-code the same on every machine?

No. Fanuc Haas GRBL LinuxCNC and Siemens all have slightly different versions of G-code. The basic codes (G00, G01, G90, G91) are universal but advanced features like high-speed machining and probing vary. Always check your machine’s manual when using a code you have not used before.

Can CAM software replace learning G-code?

CAM software generates G-code automatically but you still need to understand the output to debug problems. When a CAM-generated program crashes the machine the CAM software did not make a mistake — it generated exactly what you told it to generate. Understanding G-code lets you find and fix the issue.

Why does G-code use line numbers?

Line numbers (N10, N20, etc.) are optional labels that make programs easier to read and debug. Some controllers also use them for restarting from a specific line after an interruption. Most CAM software generates line numbers automatically.

What does the percent sign at the start and end mean?

The percent sign (%) marks the beginning and end of a G-code program on some controllers. It signals to the communication software that the program content follows. Not all controllers require it but including it does no harm.


What’s Next?

Now that you understand how G-code works at a fundamental level explore the specific codes and techniques:

What Makes a Good G-Code Program

A well-written G-code program is easy to read and debug. Use consistent line numbering in increments of 10 or 20 so you can insert new lines later without renumbering everything. Add comments to explain what each section does. Group related operations together — all setup codes first, then tool 1 operations, then tool 2 operations. A program that is easy to read is easy to debug and a program that is easy to debug is less likely to crash.

What to Do When a Program Does Not Run

When a G-code program fails to run the first step is to read the alarm message on the controller display. The message tells you which line caused the problem and why. Common alarms include undefined G-codes, missing parameters, and values outside the allowable range. Once you identify the issue correct the line in the program file and reload it.

Why Learn G-Code Manually

Even with modern CAM software understanding G-code manually is valuable. When a CAM-generated program crashes the machine you need to read the code to find the problem. When a program runs slower than expected you need to understand the code to optimize it. When a machine alarm points to line 150 you need to go to line 150 and understand what the machine was trying to do.

SERIES

G-Code Fundamentals — Part 1 of 4

  1. G-Code Explained: How CNC Programming Works
  2. G-Code for Beginners: Learn to Write Your First CNC Program
  3. G00 and G01: Rapid Traverse and Linear Interpolation
  4. G90 vs G91: Absolute vs Incremental Positioning in CNC

FAQ

Frequently Asked Questions — G-Code Fundamentals

Is G-code the same on every machine?

No. Fanuc, Haas, GRBL, LinuxCNC, and Siemens have different versions. Basic codes are universal but advanced features vary.

Can CAM software replace learning G-code?

CAM generates G-code automatically but you need to understand the output to debug problems and fix crashes.

Why does G-code use line numbers?

Line numbers are optional labels for readability and for restarting from a specific line after interruptions.

Tags:#g-code#programming#beginner