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 editor build for your current platform, operating system, and architecture. You can change what gets built by specifying a target, a platform, and/or an architecture. For example, to build an export template used for running exported games, you can run:
scons target=template_release
If you plan to debug or develop the engine, then you might want to enable the dev_build
option to enable dev-only debugging code:
scons 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.
Usando paralelismo
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 the system has 4 CPU threads or fewer, it will use all threads by default.
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 12 threads:
scons -j12
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.
To list the available target platforms, use scons platform=list:
scons platform=list
scons: Reading SConscript files ...
The following platforms are available:
android
ios
linuxbsd
macos
web
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
The resulting binaries will be placed in the bin/ subdirectory,
generally with this naming convention:
godot.<platform>.<target>[.dev][.double].<arch>[.<extra_suffix>][.<ext>]
For the previous build attempt, the result would look like this:
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
The target option controls if the editor is compiled and debug flags are used.
Optimization levels (optimize) and whether each build contains debug symbols
(debug_symbols) is controlled separately from the target. Each mode means:
target=editor: Build an editor binary (definesTOOLS_ENABLEDandDEBUG_ENABLED)target=template_debug: Build a debug export template (definesDEBUG_ENABLED)target=template_release: Build a release export template
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.
The list of command line arguments available varies depending on the build type.
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 paraverbose=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 parause_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).
When doing engine development the dev_build option can be used together
with target to enable dev-specific code. dev_build defines DEV_ENABLED,
disables optimization (-O0//0d), enables generating debug symbols, and
does not define NDEBUG (so assert() works in thirdparty libraries).
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, useoptimize=debuginstead.optimize=speed: Favors even more execution speed, at the cost of even larger binary size compared tooptimize=speed_trace. Even less friendly to debugging compared tooptimize=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=size_extra: Favors even smaller binaries, at the cost of even slower execution speed compared tooptimize=size.optimize=debug: Only enables optimizations that do not impact debugging in any way. This results in faster binaries thanoptimize=none, but slower binaries thanoptimize=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 thecflags,ccflagsandcxxflagsSCons 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.
Ver também
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:
optimize = "size"
module_mono_enabled = "yes"
use_llvm = "yes"
extra_suffix = "game_title"
You can also disable some of the built-in modules before compiling, saving some time it takes to build the engine. See Otimizando uma compilação para o tamanho page for more details.
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:
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.
Por exemplo, você pode querer forçar uma série de threads de CPU com a opção -j mencionada acima para todas as compilações futuras:
export SCONSFLAGS="-j4"
set SCONSFLAGS=-j4
$env: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 perform an 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
android_source.zip
ios.zip
linux_debug.arm32
linux_debug.arm64
linux_debug.x86_32
linux_debug.x86_64
linux_release.arm32
linux_release.arm64
linux_release.x86_32
linux_release.x86_64
macos.zip
version.txt
web_debug.zip
web_dlink_debug.zip
web_dlink_nothreads_debug.zip
web_dlink_nothreads_release.zip
web_dlink_release.zip
web_nothreads_debug.zip
web_nothreads_release.zip
web_release.zip
windows_debug_x86_32_console.exe
windows_debug_x86_32.exe
windows_debug_x86_64_console.exe
windows_debug_x86_64.exe
windows_debug_arm64_console.exe
windows_debug_arm64.exe
windows_release_x86_32_console.exe
windows_release_x86_32.exe
windows_release_x86_64_console.exe
windows_release_x86_64.exe
windows_release_arm64_console.exe
windows_release_arm64.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.