G-Code and M-Code Explained: Essential CNC Programming Languages
What Are G-Code and M-Code?
G-code and M-code form the foundational programming languages that control Computer Numerical Control (CNC) machines. These alphanumeric instruction sets tell machine tools exactly how to move, when to activate auxiliary functions, and how to execute complex machining operations. While often discussed together, they serve distinctly different purposes in the manufacturing process.
G-code (Geometric code) commands control the actual motion of the cutting tool and workpiece. These instructions define tool paths, feed rates, spindle speeds, and coordinate positioning. When you program a tool to move from point A to point B at a specific speed, you’re using G-code.
M-code (Machine code or Miscellaneous code) handles auxiliary machine functions that don’t involve direct tool movement. These commands control coolant flow, spindle rotation direction, tool changes, pallet shuttles, and other support operations that enable the machining process.
Both languages originated in the 1950s at MIT’s Servomechanisms Laboratory and were standardized through RS-274 (later evolved into ISO 6983). Despite decades of development and the introduction of conversational programming and CAM software, G-code and M-code remain the universal machine language that all CNC controllers ultimately execute.
How G-Code and M-Code Work
Program Structure and Execution
A CNC program consists of sequential blocks of code, each typically containing one or more commands that the controller executes in order. The machine controller reads each line, interprets the instructions, and sends corresponding signals to servo motors, spindles, and auxiliary systems.
A typical program block follows this structure:
- Sequence number: Optional line identifier (N10, N20, etc.) for reference and program navigation
- Preparatory commands: G-codes that establish motion modes and coordinate systems
- Dimensional data: X, Y, Z coordinates and other axis positions
- Feed rate: F value specifying cutting speed
- Spindle speed: S value defining RPM
- Tool selection: T value identifying which tool to use
- Miscellaneous functions: M-codes for auxiliary operations
Example program block: N100 G01 X50.0 Y25.0 F200 S1200 M08
This single line tells the machine to move linearly (G01) to coordinates X50, Y25 at 200 mm/min feed rate with the spindle running at 1200 RPM while activating coolant (M08).
Modal vs. Non-Modal Commands
Understanding modal behavior is critical for efficient programming. Modal commands remain active until explicitly canceled or replaced by another command in the same group. For instance, once you program G01 (linear interpolation), all subsequent moves use linear motion until you specify G00 (rapid positioning) or G02/G03 (circular interpolation).
Non-modal commands execute only in the block where they appear. M-codes are typically non-modal—M08 (coolant on) activates coolant for that block and subsequent operations until M09 (coolant off) appears.
Coordinate Systems and Work Offsets
G-code operates within defined coordinate systems that establish the relationship between programmed positions and actual machine locations. The machine has a fixed machine coordinate system with an absolute zero point, but programmers work in work coordinate systems that can be positioned anywhere within the machine’s travel range.
Work offset commands (G54 through G59 in most controllers) allow you to establish multiple coordinate systems for different part setups or fixtures. This capability is essential for multi-part production and tombstone machining where several workpieces are machined in a single program.
Essential G-Code Commands
Motion Commands
- G00 – Rapid Positioning: Moves tool at maximum traverse rate, never used for cutting
- G01 – Linear Interpolation: Straight-line cutting motion at programmed feed rate
- G02 – Circular Interpolation CW: Clockwise arc motion
- G03 – Circular Interpolation CCW: Counterclockwise arc motion
- G04 – Dwell: Programmed pause, useful for chip breaking or allowing spindle to reach speed
Coordinate System Commands
- G17/G18/G19 – Plane Selection: Defines XY, XZ, or YZ plane for circular interpolation
- G20/G21 – Unit Selection: Switches between inch and metric programming
- G28 – Return to Home: Sends machine to reference position
- G40/G41/G42 – Cutter Compensation: Cancels or activates tool radius compensation
- G43 – Tool Length Compensation: Applies tool length offset
- G54-G59 – Work Coordinate Systems: Selects active work offset
Canned Cycles
Canned cycles are pre-programmed routines that simplify repetitive operations. Rather than programming every motion explicitly, you define the cycle parameters once and the controller executes the complete sequence.
- G73 – High-Speed Peck Drilling: For deep holes with minimal chip evacuation
- G81 – Drilling Cycle: Basic spot drilling or shallow hole drilling
- G82 – Spot Facing Cycle: Drilling with dwell at bottom
- G83 – Peck Drilling Cycle: Deep hole drilling with full retract for chip clearing
- G84 – Tapping Cycle: Synchronized spindle and feed for thread cutting
- G85 – Boring Cycle: Precision hole finishing
- G86 – Boring Cycle with Spindle Stop: Prevents tool marks during retract
Essential M-Code Commands
Spindle Control
- M03 – Spindle On CW: Starts spindle clockwise rotation (standard for most operations)
- M04 – Spindle On CCW: Counterclockwise rotation (left-hand tapping, special operations)
- M05 – Spindle Stop: Halts spindle rotation
- M19 – Spindle Orientation: Positions spindle to specific angular position
Coolant Control
- M07 – Mist Coolant On: Activates mist coolant system
- M08 – Flood Coolant On: Activates flood coolant
- M09 – Coolant Off: Deactivates all coolant systems
Tool Management
- M06 – Tool Change: Executes automatic tool change sequence
- M60 – Pallet Change: Initiates pallet shuttle on machines with automatic pallet changers
Program Control
- M00 – Program Stop: Halts program execution, requires operator intervention to continue
- M01 – Optional Stop: Conditional stop activated by operator switch
- M02 – Program End: Terminates program without resetting to start
- M30 – Program End and Reset: Ends program and returns to beginning
- M98 – Subprogram Call: Executes external subroutine
- M99 – Subprogram Return: Returns from subroutine to main program
Key Specifications and Parameters
Feed Rate Specifications
Feed rate programming varies significantly between machine types and directly impacts surface finish, tool life, and cycle time. The F-word specifies feed rate, but its interpretation depends on the active feed mode.
- G94 – Feed per Minute: Most common mode, F value represents mm/min or in/min
- G95 – Feed per Revolution: F value represents mm/rev or in/rev, synchronized with spindle speed
- G93 – Inverse Time Feed: Specialized mode where F represents 1/time for the move
Typical feed rate ranges:
- Roughing operations: 500-2000 mm/min for steel, 1000-4000 mm/min for aluminum
- Finishing operations: 200-800 mm/min depending on surface finish requirements
- Rapid traverse: 10,000-60,000 mm/min depending on machine class
Spindle Speed Parameters
Spindle speed programming uses the S-word and can operate in two modes:
- G97 – Constant RPM: S value directly specifies spindle speed
- G96 – Constant Surface Speed: Controller automatically adjusts RPM to maintain constant surface footage as diameter changes (critical for turning operations)
Tolerance and Accuracy Settings
Modern controllers include commands that balance speed against accuracy:
- G61 – Exact Stop Mode: Machine decelerates to complete stop at each programmed point
- G64 – Continuous Path Mode: Machine maintains velocity through corners within tolerance band
- G05.1 – High-Speed Machining Mode: Advanced look-ahead and smoothing for complex 3D surfaces
When to Use G-Code and M-Code Programming
Manual Programming Scenarios
Direct G-code and M-code programming remains the optimal approach in specific manufacturing situations where the overhead of CAM software doesn’t justify the benefits.
- Simple 2D geometry: Drilling patterns, bolt circles, rectangular pockets, and basic profiles program faster manually than through CAM
- Short-run production: When you need 5-10 parts and CAM setup time exceeds manual programming time
- Program modifications on the shop floor: Adjusting feeds, speeds, or minor dimensional changes without returning to CAM workstation
- Prototype and R&D work: Iterative development where program flexibility and rapid changes are more important than optimization
- Educational environments: Teaching fundamental CNC concepts and machine behavior
When manual programming makes sense, investing time in learning G-code syntax pays dividends throughout your career. Even programmers who rely primarily on CAM software benefit from understanding the underlying code—it makes troubleshooting faster and gives you confidence when a program behaves unexpectedly at the machine.
When to Use CAM-Generated Code
CAM software becomes the practical choice for complex work that would take hours to program manually:
- 3D surface machining: Contoured molds, dies, and organic shapes require thousands of calculated tool positions that CAM handles in minutes
- Multi-axis operations: Simultaneous 4- and 5-axis movements demand collision checking and kinematic calculations beyond practical manual effort
- High-volume production: Optimized toolpaths and cycle time reduction justify CAM investment when running hundreds or thousands of parts
- Complex feature sequences: Parts with dozens of features benefit from CAM’s ability to organize operations, manage tool changes, and minimize non-cutting moves automatically
Regardless of how G-code is generated, understanding what the controller actually reads gives you a decisive advantage. Skilled machinists and programmers who can interpret, edit, and troubleshoot code directly at the machine reduce downtime, catch errors before they become scrapped parts, and communicate more effectively with engineers and CAM programmers. The language of CNC—G-code and M-code—remains the common foundation beneath every toolpath, every controller brand, and every machine type on the shop floor.
Conclusion
G-code and M-code form the fundamental communication layer between programmer intent and machine action, and a working knowledge of both remains essential for anyone involved in CNC manufacturing. Whether you write code manually, post-process from CAM, or simply need to verify and adjust programs at the control, understanding these commands directly improves quality, efficiency, and troubleshooting capability. Invest the time to learn the language, and every CNC machine you encounter becomes significantly easier to work with.