Open Viewer
3D View 2D View G-Code Analysis Convert About FAQ Privacy G-Code Guide

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.

G00 / G01 G02 / G03 M03 / M05 Tool Changes Lathe IJK / R MDI Part Zero
1 What is G-Code?
The language that controls CNC machines

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.

G-Code is just one type of CNC programming. The other is CAM (Computer Aided Manufacturing), where software generates G-Code automatically from a 3D model. Even if you use CAM, knowing G-Code lets you understand, debug, and hand-tune the output.

2 Why Learn G-Code?
Skills that make you a better CNC machinist

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

3 The Coordinate System
Right-handed XYZ — how your machine thinks about space

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.

X X Axis

Left–Right motion on a mill. Positive X moves the table to the right (or spindle to the left).

Y Y Axis

Front–Back motion. Positive Y moves toward the front of the machine (or spindle backward).

Z Z Axis

Up–Down motion. Positive Z moves the spindle away from the table (upward). Negative Z plunges into the part.

Important: On most mills, the table moves rather than the spindle. The coordinate directions are always described as if the spindle moves — so table motion is reversed. Always check your machine's manual for its actual axis orientation.

4-Axis, 5-Axis, and Rotational Axes

In addition to linear X, Y, Z axes, rotational axes can be added. By convention:

A Rotates around X

Tilts a part left or right. Common on 4-axis setups.

B Rotates around Y

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:

G-CODE X1Y2Z3 (no spaces — valid)
X1 Y2 Z3 (with spaces — more readable)

4 Units, Absolute & Relative Coordinates
Metric or Imperial, and two ways to describe position
G20 Inches (Imperial)

All coordinate values are interpreted as inches. Issue G20 at the start of your program if working in Imperial.

G21 Millimeters (Metric)

All coordinate values are interpreted as millimeters. Most modern CNC and 3D printing work uses G21.

Never change units in the middle of a program. Set G20 or G21 at the very beginning and stay consistent.

Absolute vs. Relative Coordinates

G90 Absolute Mode

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.

G91 Relative 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):

G-CODE G91 (switch to relative mode)
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.


5 G-Code Dialects & Post Processors
Why the same G-Code doesn't always work on every machine

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.

Most machines power up in G00 (rapids) mode, G90 (absolute), and G20 or G21 depending on configuration. Always explicitly set the modes you need at the start of any program.

6 MDI — Manual Data Input
Using your CNC like a manual machine with DROs and power feeds

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

MDI EXAMPLE G01 F20 (enter linear mode at 20 IPM — do this first!)
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 Safety: Always issue G01 with a slow feedrate first — never use G00 (rapids) in MDI until you are very experienced. Think carefully before pressing Enter. Know where the E-Stop button is before you start.

MDI Quick Reference

CommandDescription
G00Rapids 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 ZMove to specified coordinates in a straight line.
S<rpm> M03Set spindle speed and start rotating clockwise.
M04Start spindle counterclockwise.
M05Stop spindle.
M08Flood coolant on.
M07Mist/air coolant on.
M09All coolant off.

7 Basic G-Code Program Structure
Blocks, sequence numbers, comments, and word address format

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

G-CODE % (tape start — marks beginning of 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

% Tape Start/End

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.

O Program Number

Identifies the program. Fanuc style: O1000. Some controllers require 4 digits. Used for referencing subprograms.

N Sequence Numbers

Optional line numbers (N10, N20, etc.) used for reference and jumping to specific blocks. Always increment by 10 to leave room for insertions.

/ Block Skip

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:

G-CODE G00 X0 Y0 Z0 (Rapid to Part Zero)
Comment liberally. The next person to read your code — or future you — will thank you. Include program name, author, date, machine, units, and Part Zero location in the header.

8 Linear Motion — G00 & G01
Rapid positioning and feed-rate cutting in straight lines
G00 Rapid Motion

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.

G01 Feed Motion

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:

G-CODE G01 F25 X5.0 (move to X5.0 at 25 IPM)
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:

G-CODE S3000 M03 (3000 RPM, clockwise)
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:

G-CODE G00 X5 Y3 Z0.5 (all 3 axes move simultaneously to reach destination)
Tip on Z axis: When approaching a workpiece, move X and Y first, then Z separately. This prevents the cutter from hitting a clamp or raised feature as it descends. Once you are directly over your start point, then plunge in Z.

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.


9 Circular Arcs — G02 & G03
Clockwise and counterclockwise circular interpolation
G02 Clockwise Arc

Sets the controller into clockwise circular interpolation mode. Requires an endpoint and the arc center or radius.

G03 Counter-Clockwise Arc

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.

G-CODE — IJK METHOD (Arc from X0,Y2 to X2,Y0 — center at X0,Y0)
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.

G-CODE — R METHOD G02 X2 Y0 R2 F15 (clockwise arc, radius = 2)
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):

FULL CIRCLE G01 X3.25 Y2.0 (position cutter on circle)
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).

If you see crop-circle-like giant arcs in your backplot where small arcs are expected, the first thing to check is absolute vs relative IJK mismatch between your CAM post and your controller or simulator settings.

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.


10 Helical Interpolation
Arc motion combined with a Z-axis move — for thread milling and ramping

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:

HELICAL INTERPOLATION (THREAD MILLING) G01 G91 Z-0.65 F100 (plunge to start depth)
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.


11 Part Zero, Touch Offs & Work Coordinates
Telling the machine where the origin of your part is

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

Z=0 Top of Stock

Most common. Makes it easy to see when the cutter is in the material (negative Z) versus cutting air (positive Z).

Z=0 Fixed Jaw / Vise

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.


12 Tool Changes & Tool Offsets
Selecting tools and compensating for their length

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

MILL TOOL CHANGE N10 T12 (select tool 12 — ATC starts rotating it into position)
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)
Speed tip: Issue T(next tool) immediately after a tool change. This gives the ATC time to rotate the next tool into position while the machine is cutting, reducing the actual tool change time on the next M06.

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):

TOOL LENGTH OFFSET M06 (tool change)
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:

LATHE TOOL CHANGE (FANUC) T0202 (select tool 02, use wear offset 02)
T0303 (select tool 03, use wear offset 03)

13 CNC Lathe Programming
Turning, facing, and profiling on a 2-axis CNC lathe

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.

Z Z Axis — Lathe

Runs left and right, parallel to the spindle centerline. Positive Z moves the carriage away from the chuck (to the right).

X X Axis — Lathe

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

LATHE PROGRAM N10 G20 G90 G18 (inches, absolute, XZ plane)
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)

14 Automatic Chamfer & Corner Rounding (Lathe)
Adding chamfers and radii without separate arcs

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.

AUTO CHAMFER / CORNER ROUND G18 (select XZ plane)
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.


15 G-Code Quick Reference
The most commonly used G-Codes
CodeDescriptionNotes
G00Rapid positioning (maximum machine speed)Modal. Never use for cutting.
G01 F_Linear feed motion at programmed feedrateModal. Standard cutting motion.
G02Clockwise circular interpolationModal. Needs XY endpoint + IJK or R.
G03Counter-clockwise circular interpolationModal. Same syntax as G02.
G04 P_Dwell — pause for specified time (ms or sec)One-shot.
G17Select XY plane (for arcs)Default for mills. Modal.
G18Select XZ plane (for arcs)Default for lathes. Modal.
G19Select YZ plane (for arcs)Modal.
G20Set units to inches (Imperial)Modal.
G21Set units to millimeters (Metric)Modal.
G28Return to machine home positionUsually end-of-program.
G40Cancel cutter radius compensationModal.
G41Cutter radius compensation — leftModal.
G42Cutter radius compensation — rightModal.
G43 H_Apply tool length offset (positive)Modal. H = offset register number.
G49Cancel tool length offsetModal.
G54–G59Work coordinate system selectionModal. G54 is default in most programs.
G80Cancel canned cycleModal.
G81Drilling canned cycleModal.
G83Peck drilling canned cycleModal.
G90Absolute coordinate modeModal. Most programs use this.
G91Relative (incremental) coordinate modeModal.
G94Feed per minute mode (IPM or mm/min)Modal. Standard for mills.
G95Feed per revolution mode (IPR or mm/rev)Modal. Standard for lathes.
G98Return to initial Z after canned cycleModal.
G99Return to R plane after canned cycleModal.

16 M-Code Reference
Miscellaneous / auxiliary functions — spindle, coolant, program control
CodeDescriptionNotes
M00Program stop (optional stop with M01)Stops execution until operator resumes.
M01Optional program stopOnly stops if optional stop switch is on.
M02End of programStops execution. Some controllers rewind.
M03 S_Start spindle clockwise at S rpmS word can be on same or previous line.
M04Start spindle counter-clockwiseUsed for left-hand tools or tapping.
M05Stop spindleSpindle decelerates to stop.
M06 T_Tool change (execute previously selected T)Mill only. Lathe changes on T word.
M07Mist or air coolant onDepends on machine configuration.
M08Flood coolant onMost common coolant command.
M09All coolant offStops both M07 and M08.
M13Start spindle CW + flood coolantCommon on lathes.
M14Start spindle CCW + flood coolantCommon on lathes.
M19Spindle orientation (orient stop)Stops spindle at a specific angle.
M30End of program + rewindPreferred over M02. Rewinds to beginning.
M48Enable feedrate and spindle overridesAllows operator to adjust rates.
M49Disable feedrate and spindle overridesLocks rates at programmed values.
M98 P_Call subprogram (P = program number)Jumps to subprogram.
M99Return from subprogramReturns 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

HTMLEOF echo "done — $(wc -l < /home/claude/gcode-guide.html) lines"