We formulate the proper statistical mechanics to describe the stretching of a macromolecule under a force provided by the cantilever of an Atomic Force Microscope. In the limit of a soft cantilever, the generalized ensemble of the coupled molecule–cantilever system reduces to the Gibbs ensemble for an isolated molecule subject to a constant force in which the extension is fluctuating. For a stiff cantilever, one obtains the Helmholtz ensemble for an isolated molecule held at a fixed extension with the force fluctuating. Numerical examples and predictions for experiments with cantilevers of differing stiffness are given for short and long chains of poly (ethylene glycol), based on parameter-free ab initio calculations.