Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Introdução ao sistema de compilação

Godot is a primarily C++ project and it uses the SCons build system. We love SCons for how maintainable and easy to set up it makes our buildsystem. And thanks to that compiling Godot from source can be as simple as running:

scons

This produces an export template for your current platform, operating system, and architecture. An export template is a build of the engine that is used for running exported projects. To build the editor instead you can run the following command:

scons target=editor

If you plan to debug or develop the engine, then you might want to add another option to the command:

scons dev_build=yes
scons target=editor dev_build=yes

Following sections in the article will explain these and other universal options in more detail. But before you can compile Godot, you need to install a few prerequisites. Please refer to the platform documentation to learn more:

These articles cover in great detail both how to setup your environment to compile Godot on a specific platform, and how to compile for that platform. Please feel free to go back and forth between them and this article to reference platform-specific and universal configuration options.

Using multi-threading

The build process may take a while, depending on how powerful your system is. By default, Godot's SCons setup is configured to use all CPU threads but one (to keep the system responsive during compilation). If you want to adjust how many CPU threads SCons will use, use the -j <threads> parameter to specify how many threads will be used for the build.

Example for using 4 threads:

scons -j4

Seleção de plataforma

O sistema de compilação do Godot começará detectando as plataformas para as quais pode compilar. Se não for detectada, a plataforma simplesmente não aparecerá na lista de plataformas disponíveis. Os requisitos de compilação para cada plataforma são descritos no resto desta seção de tutorial.

O SCons é invocado apenas chamando scons. Se nenhuma plataforma for especificada, o SCons detectará a plataforma de destino automaticamente com base na plataforma de host. Ele vai então começar a compilar para a plataforma-alvo imediatamente.

Para listar as plataformas-alvo disponíveis, use scons platform=list:

scons platform=list
scons: Reading SConscript files ...
The following platforms are available:

    android
    javascript
    linuxbsd
    server
    windows

Please run SCons again and select a valid platform: platform=<string>

Para compilar para uma plataforma (por exemplo, linuxbsd), execute com o argumento platform= (ou p= para ficar mais curto):

scons platform=linuxbsd

Executável resultante

Os executáveis resultantes serão colocados na subpasta bin/, geralmente com esta convenção de nomenclatura:

godot.<platform>.<target>[.dev][.double].<arch>[.<extra_suffix>][.<ext>]

Para a tentativa de compilação anterior, o resultado ficaria assim:

ls bin
bin/godot.linuxbsd.editor.x86_64

Isso significa que o executável é para Linux ou *BSD (não ambos), não é otimizado, tem o editor inteiro compilado e é destinado para 64 bits.

Um executável do Windows com a mesma configuração terá esta aparência:

C:\godot> dir bin/
godot.windows.editor.64.exe

Copie esse executável para o local que você preferir, pois contém o Gerenciador de Projetos, o editor e todos os meios para executar o jogo. No entanto, faltam os dados para exportá-lo para as diferentes plataformas. Para isso, os modelos de exportação são necessários (que podem ser baixados de godotengine.org, ou você pode compilá-los você mesmo).

Além disso, existem algumas opções padrão que podem ser definidas em todos os alvos de compilação, e que serão explicadas abaixo.

Alvo

O alvo controla se o editor é contido e flags de depuração são utilizadas. Todas as compilações são otimizadas. Cada modo significa:

  • target=editor: Build with editor, optimized, with debugging code (defines: TOOLS_ENABLED, DEBUG_ENABLED, -O2//O2)

  • target=template_debug: Build with C++ debugging symbols (defines: DEBUG_ENABLED, -O2//O2)

  • target=template_release: Build without symbols (defines: -O3//O2)

O editor está habilitado por padrão em todos os alvos de PC (Linux, Windows, macOS) e desativado para o resto. Desativar o editor produz um executável que pode executar projetos, mas não inclui o editor ou o Gerenciador de Projetos.

scons platform=<platform> target=editor/template_debug/template_release

Aliases de desenvolvimento e produção

Ao criar compilações para desenvolvimento (executando ferramentas de depuração/análise), você muitas vezes tem objetivos diferentes em comparação com as compilações de produção (tornando executáveis tanto rápidos quanto pequenos aonde for possível).

O Godot fornece dois aliases para este propósito:

  • dev_mode=yes é um alias para verbose=yes warnings=extra werror=yes testing=yes. Isso permite o comportamento de avisos como erros (semelhante à configuração contínua de integração do Godot) e também compila testes de unidade para que você possa executá-los localmente.

  • production=yes é um alias para use_static_cpp=yes debug_symbols=no lto=auto. Ligar o libstdc++ dinamicamente permite melhor portabilidade do executável ao compilar para Linux. Este alias também habilita a otimização de tempo de ligação ao compilar para Linux, Web e Windows com MinGW, mas mantém a LTO desabilitada ao compilar para macOS, iOS ou Windows com MSVC. Isso ocorre porque a LTO nessas plataformas é muito lenta ou tem problemas com o código gerado.

Você pode substituir manualmente as opções desses aliases especificando-os na mesma linha de comando com valores diferentes. Por exemplo, você pode usar scons production=yes debug_symbols=yes para criar executáveis otimizados para produção com símbolos de depuração incluídos.

Compilação dev

Nota

dev_build não deve ser confundido com dev_mode, que é um alias para várias opções relacionadas ao desenvolvimento (veja acima).

Ao fazer o desenvolvimento da engine, a opção dev_build pode ser usada junto com target para ativar código específico de dev. dev_build define DEV_ENABLED, desabilita otimizações (-O0//0d), habilita a geração de símbolos de depuração, e não define ``NDEBUG` (para que ``assert()` funcione em bibliotecas de terceiros).

scons platform=<platform> dev_build=yes

Esta flag anexa o sufixo .dev (para o desenvolvimento) ao nome gerado do executável.

Ver também

Existem opções do SCons adicionais para habilitar sanitizadores, que são ferramentas que você pode habilitar em tempo de compilação para melhor depurar certos problemas da engine. Veja Using sanitizers para mais informações.

Debugging symbols

By default, debug_symbols=no is used, which means no debugging symbols are included in compiled binaries. Use debug_symbols=yes to include debug symbols within compiled binaries, which allows debuggers and profilers to work correctly. Debugging symbols are also required for Godot's crash stacktraces to display with references to source code files and lines.

The downside is that debugging symbols are large files (significantly larger than the binaries themselves). As a result, official binaries currently do not include debugging symbols. This means you need to compile Godot yourself to have access to debugging symbols.

When using debug_symbols=yes, you can also use separate_debug_symbols=yes to put debug information in a separate file with a .debug suffix. This allows distributing both files independently. Note that on Windows, when compiling with MSVC, debugging information is always written to a separate .pdb file regardless of separate_debug_symbols.

Dica

Use the strip <path/to/binary> command to remove debugging symbols from a binary you've already compiled.

Optimization level

Several compiler optimization levels can be chosen from:

  • optimize=speed_trace (default when targeting non-Web platforms): Favors execution speed at the cost of larger binary size. Optimizations may sometimes negatively impact debugger usage (stack traces may be less accurate. If this occurs to you, use optimize=debug instead.

  • optimize=speed: Favors even more execution speed, at the cost of even larger binary size compared to optimize=speed_trace. Even less friendly to debugging compared to optimize=debug, as this uses the most aggressive optimizations available.

  • optimize=size (default when targeting the Web platform): Favors small binaries at the cost of slower execution speed.

  • optimize=debug: Only enables optimizations that do not impact debugging in any way. This results in faster binaries than optimize=none, but slower binaries than optimize=speed_trace.

  • optimize=none: Do not perform any optimization. This provides the fastest build times, but the slowest execution times.

  • optimize=custom (advanced users only): Do not pass optimization arguments to the C/C++ compilers. You will have to pass arguments manually using the CFLAGS, CCFLAGS and CXXFLAGS SCons options.

Architecture

The arch option is meant to control the CPU or OS version intended to run the binaries. It is focused mostly on desktop platforms and ignored everywhere else.

Supported values for the arch option are auto, x86_32, x86_64, arm32, arm64, rv64, ppc32, ppc64 and wasm32.

scons platform=<platform> arch={auto|x86_32|x86_64|arm32|arm64|rv64|ppc32|ppc64|wasm32}

This flag appends the value of arch to resulting binaries when relevant. The default value arch=auto detects the architecture that matches the host platform.

Módulos personalizados

It's possible to compile modules residing outside of Godot's directory tree, along with the built-in modules.

A custom_modules build option can be passed to the command line before compiling. The option represents a comma-separated list of directory paths containing a collection of independent C++ modules that can be seen as C++ packages, just like the built-in modules/ directory.

For instance, it's possible to provide both relative, absolute, and user directory paths containing such modules:

scons custom_modules="../modules,/abs/path/to/modules,~/src/godot_modules"

Nota

If there's any custom module with the exact directory name as a built-in module, the engine will only compile the custom one. This logic can be used to override built-in module implementations.

Limpando arquivos gerados

Sometimes, you may encounter an error due to generated files being present. You can remove them by using scons --clean <options>, where <options> is the list of build options you've used to build Godot previously.

Alternatively, you can use git clean -fixd which will clean build artifacts for all platforms and configurations. Beware, as this will remove all untracked and ignored files in the repository. Don't run this command if you have uncommitted work!

Other build options

There are several other build options that you can use to configure the way Godot should be built (compiler, debug options, etc.) as well as the features to include/disable.

Check the output of scons --help for details about each option for the version you are willing to compile.

Sobrescrevendo as opções de compilação

Usando um arquivo

The default custom.py file can be created at the root of the Godot Engine source to initialize any SCons build options passed via the command line:

# custom.py

optimize = "size"
module_mono_enabled = "yes"
use_llvm = "yes"
extra_suffix = "game_title"

Você também pode desativar alguns dos módulos embutidos antes de compilar, economizando algum tempo para construir a engine. Veja a página ref:doc_optimizing_for_size para mais detalhes.

Ver também

You can use the online Godot build options generator to generate a custom.py file containing SCons options. You can then save this file and place it at the root of your Godot source directory.

Another custom file can be specified explicitly with the profile command line option, both overriding the default build configuration:

scons profile=path/to/custom.py

Nota

Build options set from the file can be overridden by the command line options.

It's also possible to override the options conditionally:

# custom.py

import version

# Override options specific for Godot 3.x and 4.x versions.
if version.major == 3:
    pass
elif version.major == 4:
    pass

Usando o SCONSFLAGS

SCONSFLAGS is an environment variable which is used by the SCons to set the options automatically without having to supply them via the command line.

For instance, you may want to force a number of CPU threads with the aforementioned -j option for all future builds:

export SCONSFLAGS="-j4"

SCU (single compilation unit) build

Regular builds tend to be bottlenecked by including large numbers of headers in each compilation translation unit. Primarily to speed up development (rather than for production builds), Godot offers a "single compilation unit" build (aka "Unity / Jumbo" build).

For the folders accelerated by this option, multiple .cpp files are compiled in each translation unit, so headers can be shared between multiple files, which can dramatically decrease build times.

To make a SCU build, use the scu_build=yes SCons option.

Nota

When developing a Pull Request using SCU builds, be sure to make a regular build prior to submitting the PR. This is because SCU builds by nature include headers from earlier .cpp files in the translation unit, therefore won't catch all the includes you will need in a regular build. The CI will catch these errors but it will usually be faster to catch them on a local build on your machine.

Modelos de exportação

Official export templates are downloaded from the Godot Engine site: godotengine.org. However, you might want to build them yourself (in case you want newer ones, you are using custom modules, or simply don't trust your own shadow).

If you download the official export templates package and unzip it, you will notice that most files are optimized binaries or packages for each platform:

android_debug.apk
android_release.apk
web_debug.zip
web_release.zip
linux_server_32
linux_server_64
linux_x11_32_debug
linux_x11_32_release
linux_x11_64_debug
linux_x11_64_release
macos.zip
version.txt
windows_32_debug.exe
windows_32_release.exe
windows_64_debug.exe
windows_64_release.exe

To create those yourself, follow the instructions detailed for each platform in this same tutorial section. Each platform explains how to create its own template.

The version.txt file should contain the corresponding Godot version identifier. This file is used to install export templates in a version-specific directory to avoid conflicts. For instance, if you are building export templates for Godot 3.1.1, version.txt should contain 3.1.1.stable on the first line (and nothing else). This version identifier is based on the major, minor, patch (if present) and status lines of the version.py file in the Godot Git repository.

If you are developing for multiple platforms, macOS is definitely the most convenient host platform for cross-compilation, since you can cross-compile for every target. Linux and Windows come in second place, but Linux has the advantage of being the easier platform to set this up.