{
  "id": "source-code",
  "title": "Source Code",
  "lang": "en",
  "source_lang": "en",
  "summary": "Source code is the human-readable expression of software instructions and definitions, used to build, understand, modify, and maintain computer programs.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "Program source",
    "source text"
  ],
  "generated_at": "2026-11-02",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/source-code/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/source-code/",
      "json": "https://aiwiki.page/zh/source-code.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "Source code is the representation of a computer program in a programming language, normally expressed in a form intended to be read and modified by people as well as processed by development tools. It specifies computations, organizes data, and describes interactions with other software or hardware. Source code may be written by programmers, generated by software, or produced through a combination of both. It is commonly stored as text files, although graphical programming environments and other structured systems can represent source in nontextual forms.\n\nSource code is central to software engineering because it is both an operational specification and a durable record of implementation decisions. Through compilation, interpretation, or related transformations, it determines how software behaves; through its structure, naming, comments, and history, it enables people to investigate defects, introduce features, audit security, and maintain systems over time. Possession of an executable program does not necessarily include access to its source, and access to source does not by itself confer permission to modify or redistribute it.\n\nThe meaning and practical boundaries of source code depend on the programming environment. A complete software build may require not only program files but also interface definitions, configuration, generated components, dependencies, and build instructions. Understanding source code therefore involves its linguistic form, its transformation into running software, its organization and development history, and the legal and institutional conditions under which it is shared."
    },
    {
      "heading": "Definition, boundaries, and representations",
      "text": "The term source describes a role in a transformation rather than an absolute property of a file. Code supplied to a compiler is source relative to that compilation, while the compiler’s output may become source for another tool. A program written in C, for example, can be translated into assembly language and then into machine instructions. The assembly file is generated output in the first transformation and input source in the second. Similarly, TypeScript can be translated into JavaScript, which is subsequently processed by a browser or another runtime.\n\nOrdinary source files contain declarations, expressions, statements, and other language-defined constructs. They may also contain comments, compiler directives, and annotations. File extensions such as .c, .java, and .js conventionally identify languages or processing stages, but extensions are not definitive: build tools can select a language independently of a filename. Character encoding also matters. Modern projects frequently use UTF-8, while older systems may depend on legacy encodings. A file that appears visually correct can be interpreted differently if a tool assumes the wrong encoding or treats line endings differently.\n\nThe boundary between code and data is contextual. A string stored in a database is data to the database engine but can become source code if an application submits it to a language evaluator. A configuration file may simply assign values, or it may contain expressions, conditional rules, and executable hooks. Documents written in HTML describe structure rather than general-purpose computation, but their source remains important to the behavior of web applications, especially when combined with scripts and style sheets. Consequently, “source code” is sometimes used broadly for the editable materials of a software project and sometimes narrowly for its executable logic.\n\nSource code differs from pseudocode, which communicates an algorithm without necessarily conforming to an executable language. It also differs from an executable’s raw bytes, even when those bytes can be displayed as text or interpreted by a specialist. Machine code directly encodes instructions for a processor architecture; source generally preserves higher-level concepts such as named variables, functions, and modules.\n\nThe distinction is not simply “readable” versus “unreadable.” Minified JavaScript remains source code despite being difficult to read. Conversely, a carefully formatted disassembly can be comprehensible without recovering the original source. In licensing contexts, source may be defined more specifically as the preferred form for making modifications. That definition emphasizes the materials developers actually maintain rather than any representation that happens to be textual."
    },
    {
      "heading": "Language structure and program meaning",
      "text": "A programming language gives source code both syntax and semantics. Syntax specifies which arrangements of symbols form valid programs. Semantics specifies what those arrangements mean. A compiler commonly begins by identifying tokens, such as identifiers, keywords, literals, and operators, and then parsing them into a structured representation. An abstract syntax tree records relationships such as an addition expression’s operands or a function declaration’s parameters without preserving every detail of punctuation and formatting.\n\nConsider a small C function:\n\nint maximum(int a, int b) {\n    return a > b ? a : b;\n}\n\nThe identifiers a and b denote parameters, int declares a type, and the conditional expression selects a value according to a comparison. The spelling of the identifiers has little bearing on the computation, but the scope rules, operator meanings, and type rules are essential. A language’s type system can reject certain invalid combinations before execution, while dynamically checked operations may fail only when the relevant statement runs. Successful parsing alone therefore does not establish that a program is valid or correct.\n\nSource expresses algorithms through concrete representations. Two programs can implement the same mathematical procedure while differing greatly in their data structures, memory use, error handling, and performance. A search through an unsorted sequence and a binary search through a sorted array may return the same kind of result but have different preconditions and time complexity. Understanding code requires identifying those assumptions, not merely translating statements into prose.\n\nProgram meaning also depends on context beyond a single file. Imported modules, library versions, environment variables, compiler options, and operating-system services may all affect behavior. In C, some operations have undefined behavior, meaning that the language standard imposes no requirements on the resulting execution. Signed integer overflow is a prominent example. In concurrent programs, the ordering of memory operations and the language’s memory model can determine whether a shared variable is accessed safely. These rules explain why apparently simple local edits may have consequences elsewhere.\n\nComments and names carry a different kind of meaning. They usually do not participate directly in execution, but they document intentions, invariants, and constraints that may not be obvious from statements alone. Software documentation can explain why an implementation uses a particular algorithm or avoids an otherwise plausible optimization. Such explanations are useful only while they remain consistent with the code.\n\nSome systems explicitly connect source with mathematical reasoning. Formal verification can establish that code satisfies stated properties under a specified model and assumptions. It does not make the source self-explanatory or guarantee that the properties capture every practical requirement; it provides a precise relationship between an implementation and a formal claim."
    },
    {
      "heading": "Translation, building, and execution",
      "text": "Source code reaches execution through several different processing paths. In ahead-of-time compilation, a compiler translates source into another representation before the program runs. An assembly-language representation may be an intermediate product, while object files typically contain machine instructions together with symbols and relocation information. A linker combines object files and libraries, resolves references among them, and produces an executable or shared library. Loading then places the required components into a process’s address space.\n\nAn interpreter executes a program through a software implementation of its language or intermediate representation. The distinction between compilation and interpretation is not absolute. Many systems parse source, compile it into bytecode, and execute that bytecode in a virtual machine. Just-in-time compilation can translate frequently executed portions into native instructions during execution. Java and modern JavaScript implementations illustrate different combinations of these techniques. A language is therefore not inherently confined to being “compiled” or “interpreted”; particular implementations choose particular execution strategies.\n\nA build system coordinates the transformations needed to produce usable software. It records relationships among inputs and outputs so that changed inputs trigger the necessary work. In a C project, a changed header can require recompiling several files even if their contents are unchanged. Large builds may also generate source from interface descriptions, compile resources, construct database migration packages, or assemble installation artifacts. The build dependency graph is distinct from the program’s runtime call graph, although both influence how developers understand a project.\n\nGenerated source is common. A parser generator can produce language-processing code from a grammar, while Protocol Buffers tools generate language-specific bindings from schema definitions. Generated files may be committed to a repository for distribution convenience or recreated during each build. Whether they count as the project’s authoritative source depends on the workflow. Editing a generated file directly can be ineffective if the next build overwrites the change; the durable modification belongs in the generator input or generator itself.\n\nBuild outputs are not determined by source text alone. Compiler versions, optimization settings, target architecture, library versions, filesystem paths, timestamps, and environment settings can affect the resulting bytes. A reproducible build makes it possible for independent parties, given the same specified source and build environment, to produce bit-for-bit identical designated artifacts. Achieving this often requires removing accidental environmental inputs and recording dependencies precisely.\n\nReproducibility establishes a correspondence between an artifact and a controlled build process; it does not prove that the program is safe or correct. Likewise, identical source may legitimately yield different executables for different processors or operating systems. The relationship between source and executable is therefore a documented transformation, not a universally fixed one-to-one mapping."
    },
    {
      "heading": "Organization, abstraction, and maintainability",
      "text": "Source code is organized to make a system’s complexity manageable. At the smallest scale, expressions and statements are grouped into functions or procedures. Larger units may be modules, packages, classes, libraries, or independently deployed services. These boundaries help separate responsibilities and limit the amount of implementation detail a developer must consider at once. Their effectiveness depends less on the number of files than on whether related behavior is kept together and unrelated concerns can change independently.\n\nAn application programming interface defines how one component can use another. It can specify function signatures, data types, allowed operations, and behavioral contracts. A well-defined interface allows an implementation to change without requiring all callers to change with it. Source-level compatibility is distinct from binary compatibility: a modified library might still accept recompilation of existing client source while no longer working with previously compiled clients. This distinction is particularly important in systems languages and long-lived platform libraries.\n\nAbstraction conceals selected details behind a simpler model. A collection interface, for example, may provide insertion and lookup without exposing whether the underlying representation is a tree or a hash table. Encapsulation restricts access to internal state so that changes pass through controlled operations. Neither mechanism automatically produces good design. An interface that hides essential performance characteristics or permits invalid states can make a system harder to use correctly. Effective abstractions preserve the distinctions that matter to their clients.\n\nReadability is supported by meaningful names, consistent formatting, limited nesting, explicit error handling, and documentation of nonobvious constraints. These are not merely stylistic concerns. Code is often read during tasks that demand precise judgment: diagnosing an intermittent failure, reviewing a security fix, or determining whether an old assumption still holds. A short expression that obscures evaluation order can be harder to maintain than a longer sequence with explicit steps. Conversely, unnecessary repetition can create multiple places where the same defect must be fixed.\n\nRefactoring changes internal structure while intending to preserve externally observable behavior. Examples include extracting a repeated operation into a function, separating input validation from computation, or replacing direct dependencies with an interface. Tests help detect unintended changes, but preservation of behavior can be difficult to establish when software depends on timing, undocumented side effects, or external services.\n\nAccumulated design compromises are often described as technical debt. The term covers conditions that make later changes more costly, such as duplicated logic, tightly coupled components, and obsolete dependency assumptions. It does not mean that every old implementation is defective. Compatibility requirements, constrained hardware, and stable operational behavior can justify retaining code that would not be chosen for a new system. Maintainability involves evaluating those constraints alongside the cost and risk of change."
    },
    {
      "heading": "Development workflows, review, and testing",
      "text": "Source code usually evolves through a recorded sequence of changes rather than existing as a single final document. Version control systems preserve revisions, identify differences, and support parallel development. In Git, commits record snapshots and relationships to parent commits; branches provide movable names for lines of development. A repository can therefore document not only the current implementation but also when a change entered the project and the explanation supplied with it.\n\nCollaborative workflows commonly use proposed changes that are reviewed before integration. A reviewer examines the patch in relation to surrounding code, requirements, and project conventions. Review can detect incorrect assumptions, missing error handling, inappropriate interfaces, and maintenance problems that automated checks miss. Its effectiveness depends on context and attention: a small, coherent change is generally easier to assess than an unrelated collection of modifications. Review records also preserve reasoning that would otherwise remain in private conversation.\n\nSoftware testing exercises code and compares observed behavior with expected results. Unit tests focus on relatively small components, integration tests examine interactions, and system tests assess broader behavior. Regression tests encode previously discovered failures so that later changes can be checked against them. Test coverage measures which portions of code execute during a test suite, but it does not establish that the assertions are sufficient or that all relevant inputs have been explored. Executing every line is compatible with missing an important defect.\n\nStatic program analysis examines code without running the target program in the ordinary way. Depending on the tool, it can detect type inconsistencies, suspicious control flow, unused values, possible resource leaks, or paths along which untrusted input reaches sensitive operations. Dynamic techniques complement this work. Fuzzing supplies varied or malformed inputs, while runtime instrumentation can detect invalid memory accesses or data races. Each technique has limits, including false alarms, incomplete path exploration, and dependence on the tested environment.\n\nContinuous integration automates checks when changes are submitted or incorporated. A pipeline may compile several target configurations, run tests, inspect formatting, and build release artifacts. Continuous delivery extends automation toward keeping software ready for release, but a successful pipeline is evidence only about its configured checks. A missing test or compromised build dependency can remain invisible to an otherwise functioning process.\n\nThese practices connect source changes to operational outcomes. When a defect appears, developers may use revision history to locate the introducing change, reproduce the problem in a test, and prepare a targeted correction. Release branches and backports allow the same correction to be applied to supported versions with different surrounding code. The resulting history is an important part of the engineering record, especially when a system must be maintained for years."
    },
    {
      "heading": "Historical development and changing production methods",
      "text": "Early electronic computers did not all use source code in the modern sense. Some were configured through switches, cables, and plugboards, while stored-program machines could execute instructions represented in memory. Entering instructions numerically was laborious and tied programs closely to hardware. Assembly languages introduced symbolic operation names and labels, allowing an assembler to calculate addresses and produce machine instructions. This established a durable separation between an editable symbolic representation and its executable encoding.\n\nHigher-level languages widened that separation. The first widely used FORTRAN compiler, developed under John Backus at IBM, became available in 1957. It translated mathematical and scientific expressions into machine code while seeking performance competitive with hand-written programs. COBOL, developed beginning in 1959, addressed business data processing, while ALGOL 60 helped establish influential forms of block structure and language description. These languages made it increasingly practical to express programs in terms of problems and abstractions rather than individual processor operations.\n\nSource was initially handled through media and workflows very different from contemporary editors. Punched cards often represented one source line per card, making physical order and fixed column conventions significant. Batch processing meant that a programmer might wait for a compilation listing before discovering a syntax error. Interactive terminals, time-sharing systems, and later personal computers shortened this cycle. Screen editors and integrated development environments combined editing with navigation, compilation, and debugging.\n\nDuring the 1970s, Bell Labs became a major center of systems-language development. Dennis Ritchie’s C and the development of Unix demonstrated how much of an operating system could be expressed in a relatively portable high-level language. Portability remained conditional: machine-specific code, representation assumptions, and system interfaces still required adaptation. Nevertheless, access to source made it possible to study and modify software across institutions and hardware platforms rather than treating it solely as a fixed executable product.\n\nThe growth of the Internet changed distribution and collaboration. Networked repositories, mailing lists, and later web-based development platforms allowed geographically distributed contributors to coordinate changes. The GNU project, announced by Richard Stallman in 1983, and the initial release of the Linux kernel by Linus Torvalds in 1991 became important landmarks in source-sharing development. The term “open source” gained organized prominence in 1998, alongside existing free-software traditions with their own emphasis on user freedoms.\n\nMore recent production methods include extensive code generation and assistance from large language models. These systems can propose functions, tests, explanations, or multi-file changes, but generated text still has to satisfy the language, project requirements, and dependency environment. The physical act of typing is therefore only one part of authorship and engineering responsibility. Specifications, review, testing, and control of the accepted repository remain central even when substantial portions of a draft are machine-produced."
    },
    {
      "heading": "Access, ownership, and software licensing",
      "text": "Access to source code and legal permission to use it are separate matters. Software can be distributed with readable source while retaining restrictions on modification, redistribution, commercial use, or particular fields of activity. Conversely, a user may receive broad usage rights to an executable without receiving its source. Source availability is therefore a factual property of distribution, while the permitted actions depend on the applicable license and other legal conditions.\n\nIn many jurisdictions, source code is protected by copyright as an original expression. Copyright protection is distinct from ownership of an abstract algorithm or a general programming idea. Intellectual property issues can also involve patents, trade secrets, and contractual obligations, each operating differently. Questions about employee contributions, commissioned work, and jointly developed software depend on jurisdiction and agreements. A project’s repository history can provide evidence of contributions, but a commit record does not by itself settle every question of ownership.\n\nA software license states permissions and conditions for using protected software. Permissive licenses, such as the MIT License and common BSD licenses, generally allow modification and redistribution under relatively limited conditions, including preservation of specified notices. Copyleft licenses impose additional requirements in circumstances defined by their terms. The GNU General Public License, for example, requires corresponding source to be made available when covered object code is conveyed under its conditions. The details differ among licenses and versions.\n\nOpen-source software is not simply software that can be inspected. The Open Source Definition includes requirements concerning redistribution, source availability, derived works, and nondiscrimination against persons, groups, and fields of endeavor. “Source-available” is a broader descriptive label often used for software whose code can be read but whose license does not meet those criteria. Neither label alone establishes quality, security, maintenance status, or suitability for a particular use.\n\nDependencies complicate licensing because a deliverable may combine code from many authors under different terms. Projects commonly retain license files, copyright notices, and records of third-party components. Generated source can raise additional questions when a generator copies substantial templates or runtime components into its output; the generator’s license and any explicit exceptions then matter. Automatically produced code is not exempt from provenance and licensing analysis merely because a person did not type every line.\n\nCommercial arrangements can restrict access while still providing for continuity. Source escrow places agreed materials with a third party for release under specified contractual conditions, such as a supplier’s failure to maintain a product. The usefulness of such an arrangement depends on what is deposited: source without compatible tools, dependencies, configuration, and build instructions may be insufficient to recreate or maintain the delivered system. Legal access and practical usability are thus related but distinct properties."
    },
    {
      "heading": "Security, provenance, and long-term preservation",
      "text": "Source code is a major object of security analysis because it can expose the mechanisms behind both intended behavior and vulnerabilities. Inspection may reveal missing authorization checks, unsafe parsing, or memory-management errors such as a buffer overflow. It can also reveal embedded passwords, access tokens, or private keys that should not have been committed. Removing a secret from the current revision does not remove it from repository history or from copies already obtained by others.\n\nVisibility can support independent review, but it does not guarantee that review occurs or that findings are corrected. Proprietary code can undergo rigorous internal examination, while publicly available projects may have few active maintainers. Security outcomes depend on design, review quality, testing, dependency management, and response processes rather than on source visibility alone. Source is evidence that can be analyzed, not a certificate of trustworthiness.\n\nA software supply-chain attack can target source repositories, developer accounts, dependency packages, build tools, or release infrastructure. An attacker need not alter the main project’s visible code if a compromised dependency or compiler can introduce malicious behavior later. Ken Thompson’s 1984 lecture “Reflections on Trusting Trust” described how a malicious compiler could insert behavior not apparent in the compiler’s current source and perpetuate that behavior when compiling itself. The example demonstrates that inspecting one source tree is not sufficient to establish the integrity of an entire toolchain.\n\nProvenance records connect a release to its inputs and production process. Relevant information includes the source revision, dependency versions, build instructions, toolchain, and identities or systems responsible for approval and publication. Digital signatures can establish that an artifact was signed by a particular key, assuming the verification process and key association are sound. They do not establish that the signed code is benign. Reproducible builds provide a different check by allowing independent reconstruction and comparison of designated outputs.\n\nLong-term software preservation requires more than retaining the latest source files. Historical versions, build scripts, documentation, tests, and dependency information can be necessary to understand or recreate a program. Obsolete processors, unavailable commercial libraries, discontinued network services, and missing datasets can make preserved source difficult to execute. Emulation and virtual machines can preserve aspects of the original environment, although external services and physical peripherals may remain problematic.\n\nWhen original source is lost, a decompiler may recover a higher-level representation from executable code. This reconstruction generally cannot restore all original names, comments, abstractions, or build decisions, and compiler optimization can erase distinctions between different source expressions. Archived source therefore preserves information that an executable alone often cannot supply: the implementation’s editable structure, the record of its evolution, and parts of the reasoning needed to interpret it."
    }
  ],
  "links": [
    "programming-language",
    "software-engineering",
    "compiler",
    "c-programming-language",
    "javascript",
    "utf-eight",
    "database",
    "html",
    "pseudocode",
    "machine-code",
    "abstract-syntax-tree",
    "type-system",
    "algorithm",
    "data-structure",
    "time-complexity",
    "operating-system",
    "software-documentation",
    "formal-verification",
    "assembly-language",
    "interpreter",
    "virtual-machine",
    "application-programming-interface",
    "version-control",
    "ibm",
    "personal-computer",
    "bell-labs",
    "internet",
    "linux",
    "large-language-model",
    "copyright",
    "intellectual-property",
    "software-license",
    "open-source-software",
    "cybersecurity"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}