Adaptation is conventionally regarded as occurring at the level of the individual organism. In contrast, the theory of the selfish gene proposes that it is more correct to view adaptation as occurring at the level of the gene. This view has received much popular attention, yet has enjoyed only limited uptake in the primary research literature. Indeed, the idea of ascribing goals and strategies to genes has been highly controversial. Here, we develop a formal theory of the selfish gene, using optimization theory to capture the analogy of ‘gene as fitness-maximizing agent’ in mathematical terms. We provide formal justification for this view of adaptation by deriving mathematical correspondences that translate the optimization formalism into dynamical population genetics. We show that in the context of social interactions between genes, it is the gene’s inclusive fitness that provides the appropriate maximand. Hence, genic selection can drive the evolution of altruistic genes. Finally, we use the formalism to assess the various criticisms that have been levelled at the theory of the selfish gene, dispelling some and strengthening others.