G-code


G-code, which has many variants, is the common name for the most widely used computer numerical control programming language. It is used mainly in computer-aided manufacturing to control automated machine tools.
G-code is a language in which people tell computerized machine tools how to make something. The "how" is defined by G-code instructions provided to a machine controller that tells the motors where to move, how fast to move, and what path to follow. The two most common situations are that, within a machine tool such as a lathe or mill, a cutting tool is moved according to these instructions through a toolpath cutting away material to leave only the finished workpiece and/or, an unfinished workpiece is precisely positioned in any of up to 9 axes around the 3 dimensions relative to a toolpath and, either or both can move relative to each other. The same concept also extends to noncutting tools such as forming or burnishing tools, photoplotting, additive methods such as 3D printing, and measuring instruments.

Implementations

The first implementation of a numerical control programming language was developed at the MIT Servomechanisms Laboratory in the late 1950s. In the decades since, many implementations have been developed by many organizations. G-code has often been used in these implementations. The main standardized version used in the United States was settled by the Electronic Industries Alliance in the early 1960s. A final revision was approved in February 1980 as RS-274-D. In other countries, the standard ISO 6983 is often used, but many European countries use other standards. For example, DIN 66025 is used in Germany, and PN-73M-55256 and PN-93/M-55251 were formerly used in Poland.
Extensions and variations have been added independently by control manufacturers and machine tool manufacturers, and operators of a specific controller must be aware of differences of each manufacturer's product.
One standardized version of G-code, known as BCL, is used only on very few machines. Developed at MIT, BCL was developed to control CNC machines in terms of straight lines and arcs.
During the 1970s through 1990s, many CNC machine tool builders attempted to overcome compatibility difficulties by standardizing on machine tool controllers built by Fanuc. Siemens was another market dominator in CNC controls, especially in Europe. In the 2010s, controller differences and incompatibility are not as troublesome because machining operations are usually developed with CAD/CAM applications that can output the appropriate G-code for a specific machine through a software tool called a post-processor.
Some CNC machines use "conversational" programming, which is a wizard-like programming mode that either hides G-code or completely bypasses the use of G-code. Some popular examples are Okuma's Advanced One Touch, Southwestern Industries' ProtoTRAK, Mazak's Mazatrol, Hurco's Ultimax and Winmax, Haas' Intuitive Programming System, and Mori Seiki's CAPS conversational software.
G-code began as a limited language that lacked constructs such as loops, conditional operators, and programmer-declared variables with natural-word-including names. It was unable to encode logic, but was just a way to "connect the dots" where the programmer figured out many of the dots' locations longhand. The latest implementations of G-code include macro language capabilities somewhat closer to a high-level programming language. Additionally, all primary manufacturers provide access to PLC data, such as axis positioning data and tool data, via variables used by NC programs. These constructs make it easier to develop automation applications.

Specific codes

G-codes, also called preparatory codes, are any word in a CNC program that begins with the letter G. Generally it is a code telling the machine tool what type of action to perform, such as:
There are other codes; the type codes can be thought of like registers in a computer.
It has been pointed out over the years that the term "G-code" is imprecise because "G" is only one of many letter addresses in the complete language. It comes from the literal sense of the term, referring to one letter address and to the specific codes that can be formed with it, but every letter of the English alphabet is [|used somewhere in the language]. Nevertheless, "G-code" is metonymically established as the common name of the language.

Letter addresses

Some letter addresses are used only in milling or only in turning; most are used in both. Bold below are the letters seen most frequently throughout a program.
Sources: Smid 2008; Smid 2010; Green et al. 1996.
VariableDescriptionCorollary info
Absolute or incremental position of A axis Positive rotation is defined as a counterclockwise rotation looking from [|X] positive towards X negative.
Absolute or incremental position of B axis
Absolute or incremental position of C axis
Defines diameter or radial offset used for cutter compensation. [|D] is used for depth of cut on lathes. It is used for aperture selection and commands on photoplotters.G41: left cutter compensation, G42: right cutter compensation
Precision feedrate for threading on lathes
Defines feed rateCommon units are distance per time for mills and distance per revolution for lathes
'Address for preparatory commandsG commands often tell the control what kind of motion is wanted or what offset value to use.
Defines tool length offset;
Incremental axis corresponding to C axis
G43: Negative tool length compensation, G44: Positive tool length compensation
Defines arc center in X axis for [|G02] or [|G03] arc commands.
Also used as a parameter within some fixed cycles.
The arc center is the relative distance from the current position to the arc center, not the absolute distance from the work coordinate system.
Defines arc center in [|Y] axis for G02 or G03 arc commands.
Also used as a parameter within some fixed cycles.
Same corollary info as I above.
Defines arc center in [|Z] axis for G02 or G03 arc commands.
Also used as a parameter within some fixed cycles, equal to [|L] address.
Same corollary info as I above.
Fixed cycle loop count;
Specification of what register to edit using [|G10]
Fixed cycle loop count: Defines number of repetitions of a fixed cycle at each position. Assumed to be 1 unless programmed with another integer. Sometimes the [|K] address is used instead of L. With incremental positioning, a series of equally spaced holes can be programmed as a loop rather than as individual positions.
G10 use: Specification of what register to edit.
'Miscellaneous functionAction code, auxiliary command; descriptions vary. Many M-codes call for machine functions, which is why people often say that the "M" stands for "machine", although it was not intended to.
Line number in program;
System parameter number to change using G10
Line numbers: Optional, so often omitted. Necessary for certain tasks, such as [|M99] [|P] address or GoTo statements. [|N] numbering need not increment by 1 and can be used on every block or only in certain spots throughout a program.
System parameter number: G10 allows changing of system parameters under program control.
Program nameFor example, O4501. For many years it was common for CNC control displays to use slashed zero glyphs to ensure effortless distinction of letter "O" from digit "0". Today's GUI controls often have a choice of fonts, like a PC does.
Serves as parameter address for various G and M codes
  • With [|G04], defines dwell time value.
  • Also serves as a parameter in some canned cycles, representing dwell times or other variables.
  • Also used in the calling and termination of subprograms.
Peck increment in canned cyclesFor example, [|G73], [|G83]
Defines size of arc radius, or defines retract height in milling canned cyclesFor radii, not all controls support the [|R] address for G02 and G03, in which case [|IJK] vectors are used. For retract height, the "R level", as it's called, is returned to if [|G99] is programmed.
Defines speed, either spindle speed or surface speed depending on modeData type = integer. In [|G97] mode, an integer after [|S] is interpreted as a number of rev/min. In [|G96] mode, an integer after S is interpreted as surface speed—sfm or m/min. See also Speeds and feeds. On multifunction machines, which spindle gets the input is determined by other M codes.
Tool selectionTo understand how the [|T] address works and how it interacts with [|M06], one must study the various methods, such as lathe turret programming, ATC fixed tool selection, ATC random memory tool selection, the concept of "next tool waiting", and empty tools. Programming on any particular machine tool requires knowing which method that machine uses.
Incremental axis corresponding to X axis Also defines dwell time on some machines.In these controls, X and [|U] obviate [|G90] and [|G91], respectively. On these lathes, G90 is instead [|a fixed cycle address for roughing].
Incremental axis corresponding to Y axisUntil the 2000s, the V address was very rarely used, because most lathes that used U and [|W] didn't have a Y-axis, so they didn't use V. That is still often the case, although the proliferation of live lathe tooling and turn-mill machining has made V address usage less rare than it used to be. See also [|G18].
Incremental axis corresponding to Z axis In these controls, Z and W obviate G90 and G91, respectively. On these lathes, G90 is instead a fixed cycle address for roughing.
'Absolute or incremental position of X axis.
Also defines dwell time on some machines.
'Absolute or incremental position of Y axis
Absolute or incremental position of Z axisThe main spindle's axis of rotation often determines which axis of a machine tool is labeled as Z.

List of G-codes commonly found on [FANUC] and similarly designed controls for milling and turning

Sources: Smid 2008; Smid 2010; Green et al. 1996.
CodeDescriptionMilling
Turning
Corollary info
Rapid positioningMTOn 2- or 3-axis moves, [|G00] traditionally does not necessarily move in a single straight line between start point and end point. It moves each axis at its max speed until its vector quantity is achieved. Shorter vector usually finishes first. This matters because it may yield a dog-leg or hockey-stick motion, which the programmer needs to consider, depending on what obstacles are nearby, to avoid a crash. Some machines offer interpolated rapids as a feature for ease of programming.
Linear interpolationMTThe most common workhorse code for feeding during a cut. The program specs the start and end points, and the control automatically calculates the intermediate points to pass through that yield a straight line. The control then calculates the angular velocities at which to turn the axis leadscrews via their servomotors or stepper motors. The computer performs thousands of calculations per second, and the motors react quickly to each input. Thus the actual toolpath of the machining takes place with the given feedrate on a path that is accurately linear to within very small limits.
Circular interpolation, clockwiseMTVery similar in concept to [|G01]. Again, the control interpolates intermediate points and commands the servo- or stepper motors to rotate the amount needed for the leadscrew to translate the motion to the correct tool tip positioning. This process repeated thousands of times per minute generates the desired toolpath. In the case of G02, the interpolation generates a circle rather than a line. As with G01, the actual toolpath of the machining takes place with the given feedrate on a path that accurately matches the ideal to within very small limits. In fact, the interpolation is so precise that milling an interpolated circle can obviate operations such as drilling, and often even fine boring. Addresses for radius or arc center: G02 and G03 take either an R address or IJK addresses. Cutter comp: On most controls you cannot start G41 or [|G42] in G02 or G03 modes. You must already have compensated in an earlier G01 block. Often, a short linear lead-in movement is programmed, merely to allow cutter compensation before the main action, the circle-cutting, begins. Full circles: When the arc start point and the arc end point are identical, the tool cuts a 360° arc.
Circular interpolation, counterclockwiseMTSame corollary info as for G02.
DwellMTTakes an address for dwell period. The dwell period is specified by a control parameter, typically set to milliseconds. Some machines can accept either X1.0 or P1000, which are equivalent. : Often the dwell needs only to last one or two full spindle rotations. This is typically much less than one second. Be aware when choosing a duration value that a long dwell is a waste of cycle time. In some situations it won't matter, but for high-volume repetitive production, it is worth calculating that perhaps you only need 100 ms, and you can call it 200 to be safe, but 1000 is just a waste.
P10000High-precision contour control M Uses a deep look-ahead buffer and simulation processing to provide better axis movement acceleration and deceleration during contour milling
AI Advanced Preview ControlM Uses a deep look-ahead buffer and simulation processing to provide better axis movement acceleration and deceleration during contour milling
Non-uniform rational B-spline MachiningM Activates Non-Uniform Rational B Spline for complex curve and waveform machining
Imaginary axis designationM
Exact stop check, non-modalMTThe modal version is [|G61].
Programmable data inputMTModifies the value of work coordinate and tool offsets
Data write cancelMT
XY plane selectionM
ZX plane selectionMT
YZ plane selectionM
Programming in inchesMTSomewhat uncommon except in USA and Canada and UK. However, in the global marketplace, competence with both [|G20] and [|G21] always stands some chance of being necessary at any time. The usual minimum increment in G20 is one ten-thousandth of an inch, which is a larger distance than the usual minimum increment in G21. This physical difference sometimes favors G21 programming.
Programming in millimeters MTPrevalent worldwide. However, in the global marketplace, competence with both G20 and G21 always stands some chance of being necessary at any time.
Return to home position MTTakes X Y Z addresses which define the intermediate point that the tool tip will pass through on its way home to machine zero. They are in terms of part zero, NOT machine zero.
Return to secondary home position MTTakes a P address specifying which machine zero point to use if the machine has several secondary points. Takes X Y Z addresses that define the intermediate point that the tool tip passes through on its way home to machine zero. These are expressed in terms of part zero, NOT machine zero.
Feed until skip functionM Used for probes and tool length measurement systems.
Single-point threading, longhand style TSimilar to G01 linear interpolation, except with automatic spindle synchronization for single-point threading.
Constant-pitch threadingM
Single-point threading, longhand style TSome lathe controls assign this mode to G33 rather than G32.
Variable-pitch threadingM
Tool radius compensation offMTTurn off cutter radius compensation. Cancels G41 or G42.
Tool radius compensation leftMTTurn on cutter radius compensation, left, for climb milling.
Milling: Given righthand-helix cutter and [|M03] spindle direction, G41 corresponds to climb milling. Takes an address that calls an offset register value for radius.
Turning: Often needs no D or [|H] address on lathes, because whatever tool is active automatically calls its geometry offsets with it.
G41 and G42 for milling has been partially automated and obviated since CAM programming has become more common. CAM systems let the user program as if using a zero-diameter cutter. The fundamental concept of cutter radius compensation is still in play, but the programming mindset is different. The human does not choreograph the toolpath with conscious, painstaking attention to G41, G42, and [|G40], because the CAM software takes care of that. The software has various CRC mode selections, such as computer, control, wear, reverse wear, off, some of which do not use G41/G42 at all, and others that use it so that the wear offset can still be tweaked at the machine.
Tool radius compensation rightMTTurn on cutter radius compensation, right, for conventional milling. Similar corollary info as for G41. Given righthand-helix cutter and M03 spindle direction, G42 corresponds to conventional milling.
Tool height offset compensation negativeM Takes an address, usually H, to call the tool length offset register value. The value is negative because it will be added to the gauge line position. [|G43] is the commonly used version.
Tool height offset compensation positiveM Takes an address, usually H, to call the tool length offset register value. The value is positive because it will be subtracted from the gauge line position. G44 is the seldom-used version.
Axis offset single increaseM
Axis offset single decreaseM
Axis offset double increaseM
Axis offset double decreaseM
Tool length offset compensation cancelM Cancels G43 or G44.
[|G50]Define the maximum spindle speed TTakes an S address integer, which is interpreted as rpm. Without this feature, G96 mode would rev the spindle to "wide open throttle" when closely approaching the axis of rotation.
G50Scaling function cancelM
G50Position register TPosition register is one of the original methods to relate the part coordinate system to the tool position, which indirectly relates it to the machine coordinate system, the only position the control really "knows". Not commonly programmed anymore because [|G54 to G59] are a better, newer method. Called via G50 for turning, [|G92] for milling. Those G addresses also have alternate meanings. Position register can still be useful for datum shift programming. The "manual absolute" switch, which has very few useful applications in [|WCS] contexts, was more useful in position register contexts, because it allowed the operator to move the tool to a certain distance from the part and then declare to the control what the distance-to-go shall be.
Local coordinate system M Temporarily shifts program zero to a new location. It is simply "an offset from an offset", that is, an additional offset added onto the WCS offset. This simplifies programming in some cases. The typical example is moving from part to part in a multipart setup. With [|G54] active, G52 X140.0 Y170.0 shifts program zero 140 mm over in X and 170 mm over in Y. When the part "over there" is done, G52 X0 Y0 returns program zero to normal G54. The same result can also be achieved using multiple WCS origins, G54/G55/G56/G57/G58/G59; on newer controls, G54.1 P1/P2/P3/etc. ; or using G10 for programmable data input, in which the program can write new offset values to the offset registers. The method to use depends on shop-specific application.
Machine coordinate systemMTTakes absolute coordinates with reference to machine zero rather than program zero. Can be helpful for tool changes. Nonmodal and absolute only. Subsequent blocks are interpreted as "back to G54" even if it is not explicitly programmed.
Work coordinate systems MTHave largely replaced position register. Each tuple of axis offsets relates program zero directly to machine zero. Standard is 6 tuples, with optional extensibility to 48 more via G54.1 P1 to P48.
Extended work coordinate systemsMTUp to 48 more WCSs besides the 6 provided as standard by G54 to G59. Note floating-point extension of G-code data type. Other examples have also evolved. Modern controls have the hardware to handle it.
Exact stop check, modalMTCan be canceled with [|G64]. The non-modal version is [|G09].
Automatic corner overrideMT
Default cutting mode MTCancels G61.
Rotate coordinate systemM Rotates coordinate system in the current plane given with [|G17], G18, or [|G19]. Center of rotation is given with two parameters, which vary with each vendor's implementation. Rotate with angle given with argument R. This can be used, for instance, to align the coordinate system with a misaligned part. It can also be used to repeat movement sequences around a center. Not all vendors support coordinate system rotation.
Turn off coordinate system rotationM Cancels [|G68].
Fixed cycle, multiple repetitive cycle, for finishing T
Fixed cycle, multiple repetitive cycle, for roughing T
Fixed cycle, multiple repetitive cycle, for roughing T
G73Fixed cycle, multiple repetitive cycle, for roughing, with pattern repetition T
G73Peck drilling cycle for milling – high-speed M Retracts only as far as a clearance increment. For when chipbreaking is the main concern, but chip clogging of flutes is not. Compare G83.
[|G74]Peck drilling cycle for turning T
G74Tapping cycle for milling, lefthand thread, [|M04 spindle direction]M See notes at [|G84].
Peck grooving cycle for turning T
[|G76]Fine boring cycle for millingM Includes [|OSS] and shift
G76Threading cycle for turning, multiple repetitive cycle T
Cancel canned cycleMTMilling: Cancels all cycles such as G73, [|G81], G83, etc. Z-axis returns either to Z-initial level or [|R level], as programmed.
Turning: Usually not needed on lathes, because a new group-1 G address cancels whatever cycle was active.
Simple drilling cycleM No dwell built in
Drilling cycle with dwellM Dwells at hole bottom for the number of milliseconds specified by the P address. Good for when hole bottom finish matters. Good for spot drilling because the divot is certain to clean up evenly. Consider the "choosing dwell duration" note at G04.
Peck drilling cycle M Returns to R-level after each peck. Good for clearing flutes of chips. Compare G73.
Tapping cycle, righthand thread, M03 spindle directionM G74 and G84 are the righthand and lefthand "pair" for old-school tapping with a non-rigid toolholder. Compare the rigid tapping "pair", G84.2 and G84.3.
Tapping cycle, righthand thread, M03 spindle direction, rigid toolholderM See notes at G84. Rigid tapping synchronizes speed and feed according to the desired thread helix. That is, it synchronizes degrees of spindle rotation with microns of axial travel. Therefore, it can use a rigid toolholder to hold the tap. This feature is not available on old machines or newer low-end machines, which must use "tapping head" motion.
Tapping cycle, lefthand thread, [|M04] spindle direction, rigid toolholderM See notes at G84 and G84.2.
boring cycle, feed in/feed outM
  • Good cycle for a reamer.
  • In some cases good for single-point boring tool, although in other cases the lack of depth of cut on the way back out is bad for surface finish, in which case, G76 can be used instead.
  • If need dwell at hole bottom, see [|G89].
boring cycle, feed in/spindle stop/rapid outM Boring tool leaves a slight score mark on the way back out. Appropriate cycle for some applications; for others, G76 can be used instead.
boring cycle, backboringM For backboring. Returns to initial level only ; this cycle cannot use G99 because its R level is on the far side of the part, away from the spindle headstock.
boring cycle, feed in/spindle stop/manual operationM
boring cycle, feed in/dwell/feed outM G89 is like [|G85] but with dwell added at bottom of hole.
G90Absolute programmingMT Positioning defined with reference to part zero. Milling: Always as above.
Turning: Sometimes as above, but on most lathes, G90/G91 are not used for absolute/incremental modes. Instead, U and W are the incremental addresses and X and Z are the absolute addresses. On these lathes, G90 is instead a fixed cycle address for roughing.
G90Fixed cycle, simple cycle, for roughing T When not serving for absolute programming
Incremental programmingMT Positioning defined with reference to previous position.
Milling: Always as above.
Turning: Sometimes as above, but on most lathes, G90/G91 are not used for absolute/incremental modes. Instead, U and W are the incremental addresses and X and Z are the absolute addresses. On these lathes, G90 is a fixed cycle address for roughing.
G92Position register MT Same corollary info as at [|G50 position register].
Milling: Always as above.
Turning: Sometimes as above, but on most lathes, position register is G50.
G92Threading cycle, simple cycle T
[|G94]Feedrate per minuteMT On group type A lathes, feedrate per minute is [|G98].
G94Fixed cycle, simple cycle, for roughing T When not serving for feedrate per minute
[|G95]Feedrate per revolutionMT On group type A lathes, feedrate per revolution is G99.
Constant surface speed TVaries spindle speed automatically to achieve a constant surface speed. See speeds and feeds. Takes an S address integer, which is interpreted as sfm in G20 mode or as m/min in G21 mode.
Constant spindle speedMTTakes an S address integer, which is interpreted as rev/min. The default speed mode per system parameter if no mode is programmed.
G98Return to initial Z level in canned cycleM
G98Feedrate per minute T Feedrate per minute is G94 on group type B.
G99Return to R level in canned cycleM
G99Feedrate per revolution T Feedrate per revolution is G95 on group type B.
G100Tool length measurementM

List of M-codes commonly found on FANUC and similarly designed controls for milling and turning

Sources: Smid 2008; Smid 2010; Green et al. 1996.
Some older controls require M codes to be in separate blocks.
Code DescriptionMilling
Turning
Corollary info
Compulsory stopMTNon-optional—machine always stops on reaching M00 in the program execution.
Optional stopMTMachine only stops at M01 if operator pushes the optional stop button.
End of programMTProgram ends; execution may or may not return to program top ; may or may not reset register values. [|M02] was the original program-end code, now considered obsolete, but still supported for backward compatibility. Many modern controls treat M02 as equivalent to [|M30]. See M30 for additional discussion of control status upon executing M02 or M30.
Spindle on MTThe speed of the spindle is determined by the address S, in either revolutions per minute or surface feet per minute or meters per minute. The right-hand rule can be used to determine which direction is clockwise and which direction is counter-clockwise.
Right-hand-helix screws moving in the tightening direction are defined as moving in the M03 direction, and are labeled "clockwise" by convention. The M03 direction is always M03 regardless of local vantage point and local CW/CCW distinction.
Spindle on MTSee comment above at M03.
Spindle stopMT
Automatic [|tool change] MT Many lathes do not use M06 because the T address itself indexes the turret.
Programming on any particular machine tool requires knowing which method that machine uses. To understand how the T address works and how it interacts with M06, one must study the various methods, such as lathe turret programming, ATC fixed tool selection, ATC random memory tool selection, the concept of "next tool waiting", and empty tools.
Coolant on MT
Coolant on MT
Coolant offMT
Pallet clamp onM For machining centers with pallet changers
Pallet clamp offM For machining centers with pallet changers
Spindle on and coolant on M This one M-code does the work of both M03 and [|M08]. It is not unusual for specific machine models to have such combined commands, which make for shorter, more quickly written programs.
Spindle orientationMTSpindle orientation is more often called within cycles or during setup, but it is also available under program control via [|M19]. The abbreviation OSS may be seen in reference to an oriented stop within cycles.
The relevance of spindle orientation has increased as technology has advanced. Although 4- and 5-axis contour milling and CNC single-pointing have depended on spindle position encoders for decades, before the advent of widespread live tooling and mill-turn/turn-mill systems, it was not as often relevant in "regular" machining for the operator to know the angular orientation of a spindle as it is today, except in certain contexts. Most milling of features indexed around a turned workpiece was accomplished with separate operations on indexing head setups; in a sense, indexing heads were originally invented as separate pieces of equipment, to be used in separate operations, which could provide precise spindle orientation in a world where it otherwise mostly didn't exist. But as CAD/CAM and multiaxis CNC machining with multiple rotary-cutter axes becomes the norm, even for "regular" applications, machinists now frequently care about stepping just about any spindle through its 360° with precision.
Mirror, X-axisM
M21Tailstock forward T
Mirror, Y-axisM
M22Tailstock backward T
Mirror OFFM
M23Thread gradual pullout ON T
Thread gradual pullout OFF T
End of program, with return to program topMTToday, M30 is considered the standard program-end code, and returns execution to the top of the program. Most controls also still support the original program-end code, M02, usually by treating it as equivalent to M30. Additional info: Compare M02 with M30. First, M02 was created, in the days when the punched tape was expected to be short enough to splice into a continuous loop. The other program-end code, M30, was added later to accommodate longer punched tapes, which were wound on a reel and thus needed rewinding before another cycle could start. On many newer controls, there is no longer a difference in how the codes are executed—both act like M30.
Gear select – gear 1 T
Gear select – gear 2 T
Gear select – gear 3 T
Gear select – gear 4 T
Feedrate override allowedMT[|MFO]
Feedrate override NOT allowedMTPrevent MFO. This rule is also usually called within tapping cycles or single-point threading cycles, where feed is precisely correlated to speed. Same with [|SSO] and feed hold button. Some controls are capable of providing [|SSO and MFO during threading].
Unload Last tool from spindleMTAlso empty spindle.
Automatic pallet change M For machining centers with pallet changers
Subprogram callMTTakes an address P to specify which subprogram to call, for example, "M98 P8979" calls subprogram O8979.
Subprogram endMTUsually placed at end of subprogram, where it returns execution control to the main program. The default is that control returns to the block following the [|M98] call in the main program. Return to a different block number can be specified by a P address. M99 can also be used in main program with block skip for endless loop of main program on bar work on lathes.

Example program

This is a generic program that demonstrates the use of G-Code to turn a part that is 1" diameter by 1" long. Assume that a bar of material is in the machine and that the bar is slightly oversized in length and diameter and that the bar protrudes by more than 1" from the face of the chuck.
BlockCodeDescription
%Signals start of data during file transfer. Originally used to stop tape rewind, not necessarily start of program. For some controls the first LF is start of program. ISO uses %, EIA uses ER.
O4968 Sample face and turn program. Comments are enclosed in parentheses.
N01M216Turn on load monitor
N02G20 G90 G54 D200 G40Inch units. Absolute mode. Activate work offset. Activate tool offset. Deactivate tool nose radius compensation.
Significance: This block is often called the safe block or safety block. Its commands can vary but are usually similar to the ones shown here. The idea is that a safety block should always be given near the top of any program, as a general default, unless some very specific/concrete reason exists to omit it. The safety block is like a sanity check or a preflight checklist: it explicitly ensures conditions that otherwise would be implicit, left merely to assumption. The safety block reduces risk of crashes, and it can also helpfully refocus the thinking of the humans who write or read the program under hurried conditions.
N03G50 S2000Set maximum spindle speed in rev/min — This setting affects Constant Surface Speed mode
N04T0300Index turret to tool 3. Clear wear offset.
N05G96 S854 M03Constant surface speed , 854 sfm, start spindle CW rotation
N06G41 G00 X1.1 Z1.1 T0303 M08Enable cutter radius compensation mode, rapid position to 0.55" above axial centerline and 1.1 inches positive from the work offset in Z, activate flood coolant
N07G01 Z1.0 F.05Feed in horizontally at rate of 0.050" per revolution of the spindle until the tool is positioned 1" positive from the work offset
N08X-0.016Feed the tool slightly past center—the tool must travel by at least its nose radius past the center of the part to prevent a leftover scallop of material.
N09G00 Z1.1Rapid positioning; retract to start position
N10X1.0Rapid positioning; next pass
N11G01 Z0.0 F.05Feed in horizontally cutting the bar to 1" diameter all the way to the datum, 0.05in/rev
N12G00 X1.1 M05 M09Clear the part, stop the spindle, turn off the coolant
N13G91 G28 X0Home X axis — return the machine's home position for the X axis
N14G91 G28 Z0Home Z axis — return to machine's home position for the Z axis
N15G90Return to absolute mode. Turn off load monitor
N16M30Program stop, rewind to top of program, wait for cycle start
%Signal end of data during file transfer. Originally used to mark end of tape, not necessarily end of program. ISO uses %, EIA uses ER.

Several points to note:
  1. There is room for some programming style, even in this short program. The grouping of codes in line N06 could have been put on multiple lines. Doing so may have made it easier to follow program execution.
  2. Many codes are modal, meaning they remain in effect until cancelled or replaced by a contradictory code. For example, once variable speed cutting had been selected, it stays in effect until the end of the program. In operation, the spindle speed increases as the tool nears the center of the work to maintain constant surface speed. Similarly, once rapid feed is selected, all tool movements are rapid until a feed rate code is selected.
  3. It is common practice to use a load monitor with CNC machinery. The load monitor stops the machine if the spindle or feed loads exceed a preset value that is set during the set-up operation. The jobs of the load monitor are various:
  4. # Prevent machine damage in the event of tool breakage or a programming mistake.
  5. ## This is especially important because it allows safe "lights-out machining", in which the operators set up the job and start it during the day, then go home for the night, leaving the machines running and cutting parts during the night. Because no human is around to hear, see, or smell a problem such as a broken tool, the load monitor serves an important sentry duty. When it senses overload condition, which semantically suggests a dull or broken tool, it commands a stop to the machining. Technology is available nowadays to send an alert to someone remotely if desired, which can allow them to come intercede and get production going again, then leave once more. This can be the difference between profitability or loss on some jobs, because lights-out machining reduces labor hours per part.
  6. # Warn of a tool that is becoming dull and must be replaced or sharpened. Thus, an operator tending multiple machines is told by a machine, essentially, "Pause what you're doing over there, and come attend to something over here."
  7. It is common practice to bring the tool in rapidly to a "safe" point that is close to the part—in this case 0.1" away—and then start feeding the tool. How close that "safe" distance is, depends on the preference of the programmer and/or operator and the maximum material condition for the raw stock.
  8. If the program is wrong, there is a high probability that the machine will crash, or ram the tool into the part, vice, or machine under high power. This can be costly, especially in newer machining centers. It is possible to intersperse the program with optional stops that let the program run piecemeal for testing purposes. The optional stops remain in the program but are skipped during normal running. Fortunately, most CAD/CAM software ships with CNC simulators that display the movement of the tool as the program executes. Nowadays the surrounding objects are included in the 3D models, and the simulation is much like an entire video game or virtual reality environment, making unexpected crashes much less likely. Many modern CNC machines also allow programmers to execute the program in a simulation mode and observe the operating parameters of the machine at a particular execution point. This enables programmers to discover semantic errors before losing material or tools to an incorrect program. Depending on the size of the part, wax blocks may be used for testing purposes as well. Additionally, many machines support operator overrides for both rapid and feedrate that can be used to reduce the speed of the machine, allowing operators to stop program execution before a crash occurs.
  9. For educational purposes, line numbers have been included in the program above. They are usually not necessary for operation of a machine, and increase file sizes, so they are seldom used in industry. However, if branching or looping statements are used in the code, then line numbers may well be included as the target of those statements.
  10. Some machines do not allow multiple M codes in the same line.

    Programming environments

G-code's programming environments have evolved in parallel with those of general programming—from the earliest environments to the latest environments that combine CAD, CAM, and richly featured G-code editors.
Two high-level paradigm shifts have been abandoning "manual programming" for :Category:Computer-aided manufacturing software|CAM software systems that generate G-code automatically via postprocessors, and abandoning hardcoded constructs for parametric ones. Macro CNC programming uses human-friendly variable names, relational operators, and loop structures, much as general programming does, to capture information and logic with machine-readable semantics. Whereas older manual CNC programming could only describe particular instances of parts in numeric form, macro programming describes abstractions that can easily apply in a wide variety of instances. The difference has many analogues, both from before the computing era and from after its advent, such as creating text as bitmaps versus using character encoding with glyphs; the abstraction level of tabulated engineering drawings, with many part dash numbers parametrically defined by the one same drawing and a parameter table; or the way that HTML passed through a phase of using content markup for presentation purposes, then matured toward the CSS model. In all these cases, a higher layer of abstraction introduced what was missing semantically.
STEP-NC reflects the same theme, which can be viewed as yet another step along a path that started with the development of machine tools, jigs and fixtures, and numerical control, which all sought to "build the skill into the tool." Recent developments of G-code and STEP-NC aim to build the information and semantics into the tool. This idea is not new; from the beginning of numerical control, the concept of an end-to-end CAD/CAM environment was the goal of such early technologies as DAC-1 and APT. Those efforts were fine for huge corporations like GM and Boeing. However, small and medium enterprises went through an era of simpler implementations of NC, with relatively primitive "connect-the-dots" G-code and manual programming until CAD/CAM improved and disseminated throughout industry.
Any machine tool with a great number of axes, spindles, and tool stations is difficult to program well manually. It has been done over the years, but not easily. This challenge has existed for decades in CNC screw machine and rotary transfer programming, and it now also arises with today's newer machining centers called "turn-mills", "mill-turns", "multitasking machines", and "multifunction machines". Now that CAD/CAM systems are widely used, CNC programming requires CAD/CAM to be practical and competitive in the market segments these classes of machines serve. As Smid says, "Combine all these axes with some additional features, and the amount of knowledge required to succeed is quite overwhelming, to say the least." At the same time, however, programmers still must thoroughly understand the principles of manual programming and must think critically and second-guess some aspects of the software's decisions.
Since about the mid-2000s, it seems "the death of manual programming" may be approaching. However, it is currently only in some contexts that manual programming is obsolete. Plenty of CAM programming takes place nowadays among people who are rusty on, or incapable of, manual programming—but it is not true that all CNC programming can be done, or done as well or as efficiently, without knowing G-code. Tailoring and refining the CNC program at the machine is an area of practice where it can be easier or more efficient to edit the G-code directly rather than editing the CAM toolpaths and re-post-processing the program.
Making a living cutting parts on computer-controlled machines has been made both easier and harder by CAD/CAM software. Efficiently written G-code can be a challenge for CAM software. Ideally a CNC machinist should know both manual and CAM programming well, so that the benefits of both brute-force CAM and elegant hand programming can be used where needed. Many older machines were built with limited computer memory at a time when memory was very expensive; 32K was considered plenty of room for manual programs whereas modern CAM software can post gigabytes of code. CAM excels at getting a program out quick that may take up more machine memory and take longer to run. This often makes it quite valuable to machining a low quantity of parts. But a balance must be struck between the time it takes to create a program and the time the program takes to machine a part. It has become easier and faster to make just a few parts on the newer machines with lots of memory. This has taken its toll on both hand programmers and manual machinists. Given natural turnover into retirement, it is not realistic to expect to maintain a large pool of operators who are highly skilled in manual programming when their commercial environment mostly can no longer provide the countless hours of deep experience it took to build that skill; and yet the loss of this experience base can be appreciated, and there are times when such a pool is sorely missed, because some CNC runs still cannot be optimized without such skill.

Abbreviations used by programmers and operators

This list is only a selection and, except for a few key terms, mostly avoids duplicating the many abbreviations listed at engineering drawing abbreviations and symbols.
AbbreviationExpansionCorollary info
automatic pallet changerSee [|M60].
automatic tool changerSee M06.
computer-aided design and computer-aided manufacturing
counterclockwiseSee M04.
computerized numerical control
cutter radius compensationSee also G40, G41, and G42.
cutting speedReferring to cutting speed in surface feet per minute or meters per minute.
constant surface speedSee G96 for explanation.
clockwiseSee M03.
direct numerical control or distributed numerical control Sometimes referred to as "Drip Feeding" or "Drip Numerical Control" due to the fact that a file can be "drip" fed to a machine, line by line, over a serial protocol such as RS232. DNC allows machines with limited amounts of memory to run larger files.
DOCdepth of cutRefers to how deep a given cut will be
end of blockThe G-code synonym of end of line . A control character equating to newline. In many implementations of G-code, a semicolon is synonymous with EOB. In some controls it must be explicitly typed and displayed. Other software treats it as a nonprinting/nondisplaying character, much like word processing apps treat the pilcrow.
emergency stop
externalOn the operation panel, one of the positions of the mode switch is "external", sometimes abbreviated as "EXT", referring to any external source of data, such as tape or DNC, in contrast to the computer memory that is built into the CNC itself.
full indicator movement
feet per minuteSee [|SFM].
horizontal boring millA type of machine tool that specializes in boring, typically large holes in large workpieces.
horizontal machining center
high speed machiningRefers to machining at speeds considered high by traditional standards. Usually achieved with special geared-up spindle attachments or with the latest high-rev spindles. On modern machines HSM refers to a cutting strategy with a light, constant chipload and high feedrate, usually at or near full depth of cut.
high speed steelA type of tool steel used to make cutters. Still widely used today although carbide and others continue to erode its share of commercial applications due to their higher rate of material removal.
inch
inches per fluteAlso known as chip load or [|IPT]. See [|F address] and feed rate.
inches per minuteSee F address and feed rate.
inches per revolutionSee F address and feed rate.
inches per toothAlso known as chip load or [|IPF]. See F address and feed rate.
manual data inputA mode of operation in which the operator can type in lines of program and then execute them by pushing cycle start.
memoryOn the operation panel, one of the positions of the mode switch is "memory", sometimes abbreviated as "MEM", referring to the computer memory that is built into the CNC itself, in contrast to any external source of data, such as tape or DNC.
manual feedrate overrideThe MFO dial or buttons allow the CNC operator or machinist to multiply the programmed feed value by any percentage typically between 10% and 200%. This is to allow fine-tuning of speeds and feeds to minimize chatter, improve surface finish, lengthen tool life, and so on. The SSO and MFO features can be locked out for various reasons, such as for synchronization of speed and feed in threading, or even to prevent "soldiering"/"dogging" by operators. On some newer controls, the synchronization of speed and feed in threading is sophisticated enough that SSO and MFO can be available during threading, which helps with fine-tuning speeds and feeds to reduce chatter on the threads or in repair work involving the picking up of existing threads.
millimetre
manual pulse generatorReferring to the handle
numerical control
oriented spindle stopSee comments at M19.
surface feet per minuteSee also speeds and feeds and G96.
surface feet per minuteSee also speeds and feeds and G96.
single-point threading
spindle speed overrideThe SSO dial or buttons allow the CNC operator or machinist to multiply the programmed speed value by any percentage typically between 10% and 200%. This is to allow fine-tuning of speeds and feeds to minimize chatter, improve surface finish, lengthen tool life, and so on. The SSO and MFO features can be locked out for various reasons, such as for synchronization of speed and feed in threading, or even to prevent "soldiering"/"dogging" by operators. On some newer controls, the synchronization of speed and feed in threading is sophisticated enough that SSO and MFO can be available during threading, which helps with fine-tuning speeds and feeds to reduce chatter on the threads or in repair work involving the picking up of existing threads.
or T/Ctool change, tool changer See M06.
total indicator reading
threads per inch
Universal Serial BusOne type of connection for data transfer
vertical machining center
vertical turret latheA type of machine tool that is essentially a lathe with its Z axis turned vertical, allowing the faceplate to sit like a large turntable. The VTL concept overlaps with the vertical boring mill concept.

Extended developments