G-Code Complete Guide — A to Z
Everything you need to learn G-Code from scratch. Covers coordinate systems, all motion commands, circular arcs, MDI, program structure, tool changes, and CNC lathe programming — with examples and code snippets throughout.
G-Code is the language used to control CNC machines. It tells the machine exactly how to move — where to go, how fast, and what to do. It is the Lingua Franca of CNC: used by CNC mills, lathes, routers, laser cutters, and 3D printers worldwide.
In order to make a part on a CNC machine, you write a G-Code program that describes every move the cutter must make. The machine's controller reads these instructions and moves the axes accordingly.
Armed with a solid understanding of G-Code, you can:
- Avoid running back to your CAM program when simple edits to the G-Code would do the job faster
- Understand and improve the G-Code your CAM program produces for better surface finish and cycle times
- Tweak your CAM post processor so it produces better code from the start
- Get a second opinion on CAM G-Code before finding out something is wrong at the machine
- Fix G-Code bugs quickly — a misplaced move that would otherwise require re-running the entire CAM workflow
- Create quick hand-written programs for simple parts without touching CAD/CAM at all
- Develop greater skill at the machine console, including MDI operation
CNC machines use a Right-Handed Coordinate System. Hold up your right hand with your index finger extended, thumb pointing up, and middle finger extended at right angles: your middle finger is X, index finger is Y, thumb is Z.
Left–Right motion on a mill. Positive X moves the table to the right (or spindle to the left).
Front–Back motion. Positive Y moves toward the front of the machine (or spindle backward).
Up–Down motion. Positive Z moves the spindle away from the table (upward). Negative Z plunges into the part.
4-Axis, 5-Axis, and Rotational Axes
In addition to linear X, Y, Z axes, rotational axes can be added. By convention:
Tilts a part left or right. Common on 4-axis setups.
Tilts a part forward or backward. Used on 5-axis machines with trunnion tables.
Rotational axes use degrees as their unit. Example: A90 rotates the 4th axis to 90°.
Expressing Coordinates in G-Code
Simply take the axis letter and add the value. Spaces are optional:
X1 Y2 Z3 (with spaces — more readable)
All coordinate values are interpreted as inches. Issue G20 at the start of your program if working in Imperial.
All coordinate values are interpreted as millimeters. Most modern CNC and 3D printing work uses G21.
Absolute vs. Relative Coordinates
All coordinates refer to the origin (0,0,0). X10 always means 10 units from origin, regardless of where the tool is now. This is the most common mode.
All coordinates are relative to the current position. X10 means move 10 units in the X direction from wherever you are now.
Example — cutting a 1″ square using relative mode (G91):
X1 (move 1" right)
Y1 (move 1" up in Y)
X-1 (move 1" left)
Y-1 (move 1" down — back to start)
G90 (switch back to absolute)
Offsets
Offsets are a way to shift the coordinate origin. Work Offsets (G54–G59) let you define multiple "Part Zeros" on the machine table at the same time — for example, to machine two identical parts held in separate vises without changing the program.
G-Code is not perfectly standardized. Different CNC controllers implement different dialects. The most common dialects are Fanuc (professional shops) and Mach3/LinuxCNC (hobbyists). Key differences include:
- Supported G-Codes: Not all controllers support all G-Codes. Early lathe controls often lack G71 roughing cycles.
- G-Code mappings: The same function may use different code numbers on different controllers.
- Formatting: Some controllers require G00, others accept G0. Some require decimal points: "1." vs "1.0" vs "1".
- Parameters: The letters used to pass additional information to a G-Code can vary between dialects.
- Macro Programming: Fanuc Macro B is the most common standard, but support varies widely.
Post Processors
If you use CAM software, it has a Post Processor (or "Post") that converts geometry moves into the specific G-Code dialect your machine needs. The Post is what ensures your CAM output is compatible with your controller. If you frequently make the same hand edits to your G-Code output, it's worth investigating whether a Post change would eliminate that work permanently.
Modal Behavior
G-Code is a modal language. Many commands set a "mode" that stays active until you change it. For example, once you issue G01 (feed motion), the machine stays in feed motion mode. You don't need to repeat G01 on every line — only when you want to change to a different mode.
MDI (Manual Data Input) lets you type G-Code commands directly into the CNC controller for immediate execution — no program file needed. Think of it as giving the machine orders one line at a time, exactly like a manual mill with digital readouts and power feeds on every axis.
Basic MDI Workflow
S4000 M03 (set spindle to 4000 RPM, start clockwise)
M08 (flood coolant on)
X1.0 (feed to X=1.0 at 20 IPM)
M05 (stop spindle)
M09 (coolant off)
MDI Quick Reference
| Command | Description |
|---|---|
| G00 | Rapids mode — fastest possible speed. Avoid in MDI until experienced. |
| G01 F<ipm> | Linear feed mode at the specified feedrate. Use this for MDI movement. |
| X Y Z | Move to specified coordinates in a straight line. |
| S<rpm> M03 | Set spindle speed and start rotating clockwise. |
| M04 | Start spindle counterclockwise. |
| M05 | Stop spindle. |
| M08 | Flood coolant on. |
| M07 | Mist/air coolant on. |
| M09 | All coolant off. |
A line of G-Code is called a Block. A complete G-Code program is made of many blocks executed in sequence from top to bottom.
A Minimal G-Code Program
(-----------------------------------------------)
( Program: simple_face.nc )
( Author: Your Name — Date: 2026-05-01 )
( Machine: Fanuc Mill, Inches )
( Part Zero: Top of stock, front-left corner )
(-----------------------------------------------)
O1000 (program number)
N10 G20 G90 G17 (inches, absolute, XY plane)
N20 S3000 M03 (3000 RPM, spindle CW)
N30 G00 X0 Y0 Z0.5 (rapid to safe position)
N40 G01 Z-0.1 F10 (plunge to depth at 10 IPM)
N50 X5.0 F30 (face mill pass at 30 IPM)
N60 G00 Z0.5 (rapid up to safe Z)
N70 M05 (stop spindle)
N80 M30 (end program, rewind)
% (tape end)
Block Structure Elements
Marks the absolute beginning and end of a G-Code file. Not required by all controllers but good practice. Anything after the closing % is ignored.
Identifies the program. Fanuc style: O1000. Some controllers require 4 digits. Used for referencing subprograms.
Optional line numbers (N10, N20, etc.) used for reference and jumping to specific blocks. Always increment by 10 to leave room for insertions.
Start a line with "/" to allow the operator to optionally skip that line via the control panel. Useful for optional operations.
Word Address Format
Every letter in G-Code is a Word. The number following it is its Address. For example: X1.5 — X is the word, 1.5 is the address. The letter always tells the controller what kind of information is coming next, and the number tells it the value.
Order of Execution Within a Block
Words in a block do not necessarily execute left to right. The controller has a defined order of operations: set feedrate mode → set feedrate → set spindle speed → select tool → change tool → spindle on/off → coolant → motion. If you are unsure about the order, put commands in separate blocks to guarantee sequence.
Comments
Anything inside parentheses is a comment and is completely ignored during execution:
Moves at the maximum possible speed of the machine. Used to position the cutter near the cut — never enter a cut with G00. Most machines start in G00 mode on power-up.
Moves in a straight line at the programmed feedrate (F word). Used for all actual cutting moves. Required for safe MDI operation.
Feedrate — The F Word
The F word sets the cutting speed in inches per minute (IPM) or mm/min depending on units mode. The feedrate is modal — set it once and it stays until you change it:
Y3.0 (still G01 at 25 IPM — modal)
X0 Y0 (still G01 at 25 IPM)
Spindle Speed — The S Word
The S word sets spindle RPM. Use it together with M03 (CW) or M04 (CCW). Both S and F are modal:
G01 F20 Z-0.5 (plunge at 20 IPM)
Interpolated Moves
When you specify multiple axes in one block, all axes move simultaneously and arrive at the destination at the same time — this is called interpolated motion. The controller coordinates their speeds automatically:
Older Machine Warning — "Dog Leg" G00
Older controllers may "dog leg" G00 — moving one axis at a time instead of a coordinated straight line. Be very careful programming G00 moves on older machines if there are any obstacles in the path.
Sets the controller into clockwise circular interpolation mode. Requires an endpoint and the arc center or radius.
Sets the controller into counter-clockwise circular interpolation mode. Same syntax as G02.
Defining an Arc: Two Methods
Every arc needs three things: a starting point (current position), an ending point (XYZ), and the center location. There are two ways to specify the center:
Method 1 — IJK (Relative Offsets from Start Point)
I, J, K are the distances from the starting point to the center of the arc, along X, Y, Z respectively. Add I to start-X to get center-X, add J to start-Y to get center-Y.
G02 X2 Y0 I0 J-2.0 F15
(I=0 means center is 0 units from start in X)
(J=-2 means center is 2 units below start in Y)
Method 2 — R (Radius)
Simply specify the radius with the R word. Easier to write, but note: full circles cannot be programmed with R (ambiguous). For arcs over 180°, use a negative R to force the longer path.
G02 X2 Y0 R-2 F15 (same endpoints, takes the LONGER path)
Full Circles — Same Start and End Point
A full circle has identical start and end points. Must use IJK (not R — infinitely ambiguous with R):
G02 X3.25 Y2.0 I-1.25 J0 (full 360° CW circle, center 1.25 to the left)
Common Problem: Absolute vs Relative IJK
The most common configuration error when setting up a CAM post or simulator is mismatching absolute vs relative IJK. If your backplot shows giant circles instead of the expected toolpath, check this setting first. IJK is relative (offset from start point) by default on most Fanuc-style controllers, but some controllers use absolute (actual center coordinates).
Arcs for Better Toolpaths
Whenever a cutter changes direction abruptly (especially 90°), it creates stress and can leave marks in the finish. Program a small arc at each corner rather than a sharp direction change. Even a tiny radius allows the controller to avoid instantaneous direction reversal and will improve surface finish and tool life.
Arcs are also the best way to enter a cut — gradually ramping in with an arc instead of plunging straight down greatly reduces cutting forces and extends tool life.
A helix is a circular arc that simultaneously moves in a third axis (Z). Helical interpolation is used for thread milling, ramping into a pocket, and interpolating large holes. You add a Z value to a G02/G03 block to create helical motion:
G03 X0.094 Y0.094 Z0.018 R0.094 (1 helix pass, 0.018" pitch per pass)
G03 X-0.118 Y0.118 Z0.018 R0.118 (next pass, radius slightly larger)
In this thread-milling example, each arc block moves the cutter 0.018" deeper in Z while completing one revolution — creating one thread pitch per pass.
Part Zero (also called Work Zero or Program Zero) is the X0 Y0 Z0 origin point your G-Code program refers to. Before running any program, you must tell the machine where Part Zero is in relation to the machine's own coordinate system.
Where to Put Part Zero
Most common. Makes it easy to see when the cutter is in the material (negative Z) versus cutting air (positive Z).
More reliable for repeat jobs. Part Zero is on a surface that doesn't change even if you remove and replace the workpiece.
Machine Coordinates vs Work Coordinates
Machine Coordinates are fixed — they are set when you home the machine. Work Coordinates are what your G-Code program uses. You establish Work Coordinates by "touching off" — finding the edge of your part and telling the machine that location is X0, Y0, or Z0.
Touch Off Methods
- Paper method: Use a thin piece of paper (cigarette paper works well) dampened with oil. Jog the spinning cutter until it just moves the paper. Adjust for paper thickness.
- Gage block: Use a precision gage block between the stationary cutter and the workpiece surface. Jog until the block just fits with slight drag.
- Edge finder: A spinning probe that kicks off-center when it touches a workpiece edge, giving a precise X or Y zero.
- 3D Taster (Haimer): A mechanical probe that precisely finds edges and centers. Very fast and accurate.
- Renishaw probe: Electronic touch probe. Fastest and most accurate — used in production environments.
Multiple Work Coordinate Systems
G54 through G59 each define an independent Work Coordinate System. This lets you machine multiple identical parts held in separate vises — each vise gets its own Work Offset. The same program runs against each offset to machine each part.
Most CNC programs use more than one tool. Tool change codes serve two purposes: (1) physically change the tool in the spindle, and (2) load the Tool Length Offset — a value that compensates for the fact that different tools have different lengths.
Mill Tool Change — T + M06
N20 M06 (execute tool change — tool 12 is now in spindle)
N30 T14 (pre-select next tool while cutting with T12)
(... cutting with T12 ...)
M06 (change to T14)
Tool Length Offsets
Every tool has a different length. The Geometry Offset (stored in the tool table) compensates for the overall length difference. The Wear Offset is a fine-tuning adjustment for gradual tool wear and allows the machinist to hit exact tolerances without editing the program.
Use G43 to apply a tool length offset (H word references the offset register):
G43 Z0.5 H12 (apply tool length offset #12, rapid to Z0.5)
Lathe Tool Change (Fanuc Style)
On lathes, no M06 is needed — the tool changes as soon as the T word executes. Fanuc combines tool number and wear offset in one T command:
T0303 (select tool 03, use wear offset 03)
A basic CNC lathe uses only two axes: Z (parallel to the spindle) and X (perpendicular to the spindle). The same G00, G01, G02, G03 motion codes are used, but without Y.
Runs left and right, parallel to the spindle centerline. Positive Z moves the carriage away from the chuck (to the right).
Runs front to back, perpendicular to the spindle. Positive X moves the tool away from the centerline (increases diameter).
Diameter vs Radius Mode
Most lathes operate in Diameter Mode by default: X values represent the diameter of the part, not the distance from centerline. A part with a 2" diameter is programmed as X2.0, even though the tool is only 1.0" from the centerline. Check your controller's manual to verify which mode it defaults to.
Part Zero on Lathe Programs
The X-axis zero is always the spindle centerline. For Z, the three common options are:
- End of finished part — most common; easy to relate dimensions to the print
- Chuck jaw face — useful when machining both ends
- Chuck face — least useful, rarely matches the actual part position
Simple Lathe Program Example
N20 T0101 (tool 1, offset 1)
N30 S1200 M03 (1200 RPM, spindle on CW)
N40 G00 X2.2 Z0.1 (rapid to start position)
N50 G01 Z-2.0 F0.008 (turn OD to length, feed 0.008"/rev)
N60 X2.5 (face end)
N70 G00 Z0.5 (retract in Z)
N80 M05 (stop spindle)
N90 M30 (end program)
Many CNC lathe controllers support automatic chamfer and corner rounding as part of a G01 move. Instead of programming a separate G02/G03 arc, you add a C (chamfer) or R (radius) word to the G01 block and the controller inserts the feature automatically at the transition.
G00 X5 Z5 (rapid to start)
G01 Z2 R0.236 (move in Z, auto corner radius 0.236" at end)
X10 C-0.118 (move in X, auto chamfer 0.118" at end)
Z0 (final move)
Use C for a chamfer and R for a radius. The sign (positive or negative) depends on which direction you are moving and what the next direction will be — consult your controller's chart or simply try both and verify in your simulator.
| Code | Description | Notes |
|---|---|---|
| G00 | Rapid positioning (maximum machine speed) | Modal. Never use for cutting. |
| G01 F_ | Linear feed motion at programmed feedrate | Modal. Standard cutting motion. |
| G02 | Clockwise circular interpolation | Modal. Needs XY endpoint + IJK or R. |
| G03 | Counter-clockwise circular interpolation | Modal. Same syntax as G02. |
| G04 P_ | Dwell — pause for specified time (ms or sec) | One-shot. |
| G17 | Select XY plane (for arcs) | Default for mills. Modal. |
| G18 | Select XZ plane (for arcs) | Default for lathes. Modal. |
| G19 | Select YZ plane (for arcs) | Modal. |
| G20 | Set units to inches (Imperial) | Modal. |
| G21 | Set units to millimeters (Metric) | Modal. |
| G28 | Return to machine home position | Usually end-of-program. |
| G40 | Cancel cutter radius compensation | Modal. |
| G41 | Cutter radius compensation — left | Modal. |
| G42 | Cutter radius compensation — right | Modal. |
| G43 H_ | Apply tool length offset (positive) | Modal. H = offset register number. |
| G49 | Cancel tool length offset | Modal. |
| G54–G59 | Work coordinate system selection | Modal. G54 is default in most programs. |
| G80 | Cancel canned cycle | Modal. |
| G81 | Drilling canned cycle | Modal. |
| G83 | Peck drilling canned cycle | Modal. |
| G90 | Absolute coordinate mode | Modal. Most programs use this. |
| G91 | Relative (incremental) coordinate mode | Modal. |
| G94 | Feed per minute mode (IPM or mm/min) | Modal. Standard for mills. |
| G95 | Feed per revolution mode (IPR or mm/rev) | Modal. Standard for lathes. |
| G98 | Return to initial Z after canned cycle | Modal. |
| G99 | Return to R plane after canned cycle | Modal. |
| Code | Description | Notes |
|---|---|---|
| M00 | Program stop (optional stop with M01) | Stops execution until operator resumes. |
| M01 | Optional program stop | Only stops if optional stop switch is on. |
| M02 | End of program | Stops execution. Some controllers rewind. |
| M03 S_ | Start spindle clockwise at S rpm | S word can be on same or previous line. |
| M04 | Start spindle counter-clockwise | Used for left-hand tools or tapping. |
| M05 | Stop spindle | Spindle decelerates to stop. |
| M06 T_ | Tool change (execute previously selected T) | Mill only. Lathe changes on T word. |
| M07 | Mist or air coolant on | Depends on machine configuration. |
| M08 | Flood coolant on | Most common coolant command. |
| M09 | All coolant off | Stops both M07 and M08. |
| M13 | Start spindle CW + flood coolant | Common on lathes. |
| M14 | Start spindle CCW + flood coolant | Common on lathes. |
| M19 | Spindle orientation (orient stop) | Stops spindle at a specific angle. |
| M30 | End of program + rewind | Preferred over M02. Rewinds to beginning. |
| M48 | Enable feedrate and spindle overrides | Allows operator to adjust rates. |
| M49 | Disable feedrate and spindle overrides | Locks rates at programmed values. |
| M98 P_ | Call subprogram (P = program number) | Jumps to subprogram. |
| M99 | Return from subprogram | Returns to calling program. |
GCodex G-Code guide · learn g-code · g-code tutorial · g-code course · G00 G01 G02 G03 · CNC g-code reference · circular arcs gcode · tool changes g-code · lathe g-code · MDI cnc · g-code for beginners · free g-code course · gcode viewer · ncviewer alternative · gcodex.tech
GCodex