A compiler works in several stages to translate a program from a source language to an output language. It performs lexical analysis to break the source code into tokens, syntactical analysis to check syntax is correct, semantic analysis to ensure code makes logical sense, and optionally generates intermediate code before final code generation and optimization to produce the target program.