TExcelTAD
Home › Godot 4 with GDScript › GDExtension (C++) Overview

GDExtension (C++) Overview

GDExtension lets you add new classes to Godot from a shared library (.dll, .so, .dylib) without recompiling the engine. The library registers its classes with the engine at startup, and from then on they behave like built-in nodes: they appear in the Create New Node dialog, have inspector properties and signals, and GDScript and C# can use them. Most extensions are written in C++ with the official godot-cpp bindings; community bindings exist for Rust (godot-rust), Swift and others.

When to reach for it

GDScript is fast enough for gameplay logic in most games. GDExtension is for the cases where it isn't, or where you need native code:

  • CPU-heavy systems: large simulations, procedural generation, custom pathfinding over big grids, voxel meshing.
  • Wrapping a C or C++ library: a physics engine, a networking SDK, a platform SDK (Steam, for example, through community extensions such as GodotSteam).
  • Shipping a reusable addon that must be fast and doesn't depend on the .NET build.

Writing an extension means a C++ toolchain, builds per platform, and slower iteration than GDScript. Profile first. Often a typed GDScript rewrite or a built-in node (AStarGrid2D, MultiMeshInstance3D, the physics server) solves the problem. The C++ course covers the language.

Everything is a registered class

The engine itself works the same way an extension does: every class registers its methods, properties and signals in ClassDB, and scripts, the inspector and the docs all read from there. You can look at it from GDScript:

gdscript · try it yourself
extends SceneTree

func _init():
	var cls := &"Sprite2D"
	var chain: Array[String] = []
	while cls != &"":
		chain.append(cls)
		cls = ClassDB.get_parent_class(cls)
	print(" -> ".join(chain))
	print("has set_offset: ", ClassDB.class_has_method("Sprite2D", "set_offset"))
	var props := ClassDB.class_get_property_list("Sprite2D", true)
	var names := props.filter(func(p): return p.usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_SUBGROUP | PROPERTY_USAGE_CATEGORY) == 0).map(func(p): return p.name)
	print("own properties: ", names)
	print("signals: ", ClassDB.class_get_signal_list("Sprite2D", true).map(func(s): return s.name))
	print("loaded extensions: ", GDExtensionManager.get_loaded_extensions())
	print("GDExample exists: ", ClassDB.class_exists("GDExample"))
	quit()
Sprite2D -> Node2D -> CanvasItem -> Node -> Object
has set_offset: true
own properties: ["texture", "centered", "offset", "flip_h", "flip_v", "hframes", "vframes", "frame", "frame_coords", "region_enabled", "region_rect", "region_filter_clip_enabled"]
signals: ["frame_changed", "texture_changed"]
loaded extensions: []
GDExample exists: false

An extension that registers GDExample would make the last line true, and the class would show up in that same list for scripts and the editor.

Project layout

The official tutorial uses this layout: the extension source and the bindings sit next to a test project.

text
gdextension_example/
├── godot-cpp/              # the C++ bindings (git submodule, branch matching your Godot version)
├── src/
│   ├── register_types.cpp
│   ├── register_types.h
│   ├── gdexample.cpp
│   └── gdexample.h
├── SConstruct              # build script (SCons)
└── project/                # a Godot project to test with
    └── bin/
        └── gdexample.gdextension

Pick the godot-cpp branch that matches the oldest Godot version you support (for example the 4.3 branch for Godot 4.3). An extension built against an older 4.x minor version generally loads in newer ones; the reverse doesn't work.

A class in C++

The header declares a node that extends Sprite2D:

cpp
// src/gdexample.h
#pragma once
#include <godot_cpp/classes/sprite2d.hpp>

namespace godot {

class GDExample : public Sprite2D {
    GDCLASS(GDExample, Sprite2D)

    double time_passed = 0.0;
    double amplitude = 10.0;

protected:
    static void _bind_methods();

public:
    void _process(double delta) override;
    void set_amplitude(double p_amplitude);
    double get_amplitude() const;
};

}

GDCLASS(GDExample, Sprite2D) adds the boilerplate that ties the C++ class into the engine's class system. _bind_methods() tells ClassDB what to expose:

cpp
// src/gdexample.cpp
#include "gdexample.h"
#include <godot_cpp/core/class_db.hpp>

using namespace godot;

void GDExample::_bind_methods() {
    ClassDB::bind_method(D_METHOD("get_amplitude"), &GDExample::get_amplitude);
    ClassDB::bind_method(D_METHOD("set_amplitude", "p_amplitude"), &GDExample::set_amplitude);
    ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "amplitude", PROPERTY_HINT_RANGE, "0,20,0.01"),
                 "set_amplitude", "get_amplitude");
    ADD_SIGNAL(MethodInfo("position_changed",
                          PropertyInfo(Variant::OBJECT, "node"),
                          PropertyInfo(Variant::VECTOR2, "new_pos")));
}

void GDExample::_process(double delta) {
    time_passed += delta;
    Vector2 new_position(amplitude + amplitude * sin(time_passed * 2.0),
                         amplitude + amplitude * cos(time_passed * 1.5));
    set_position(new_position);
    emit_signal("position_changed", this, new_position);
}

void GDExample::set_amplitude(double p_amplitude) { amplitude = p_amplitude; }
double GDExample::get_amplitude() const { return amplitude; }

Finally, register_types.cpp exports the entry function the engine calls when it loads the library, and registers the class at the scene initialization level:

cpp
// src/register_types.cpp
#include "register_types.h"
#include "gdexample.h"
#include <gdextension_interface.h>
#include <godot_cpp/core/defs.hpp>
#include <godot_cpp/godot.hpp>

using namespace godot;

void initialize_example_module(ModuleInitializationLevel p_level) {
    if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) return;
    GDREGISTER_CLASS(GDExample);
}

void uninitialize_example_module(ModuleInitializationLevel p_level) {
    if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) return;
}

extern "C" {
GDExtensionBool GDE_EXPORT example_library_init(GDExtensionInterfaceGetProcAddress p_get_proc_address,
                                                const GDExtensionClassLibraryPtr p_library,
                                                GDExtensionInitialization *r_initialization) {
    godot::GDExtensionBinding::InitObject init_obj(p_get_proc_address, p_library, r_initialization);
    init_obj.register_initializer(initialize_example_module);
    init_obj.register_terminator(uninitialize_example_module);
    init_obj.set_minimum_library_initialization_level(MODULE_INITIALIZATION_LEVEL_SCENE);
    return init_obj.init();
}
}

What _bind_methods really does: a model

ClassDB is, at heart, a table from class and method names to callable functions, plus property descriptions that point at a setter and a getter. Here is a small runnable C++ model of that idea (no Godot involved): a class registers itself, and a "script" then sets a property and calls a method by name, the way GDScript and the inspector do.

cpp · try it yourself
#include <cmath>
#include <cstdio>
#include <functional>
#include <map>
#include <string>

struct Object { virtual ~Object() = default; };

struct PropertyInfo { std::string setter, getter; double min, max; };
struct ClassInfo {
    std::map<std::string, std::function<double(Object*, double)>> methods;
    std::map<std::string, PropertyInfo> properties;
};
std::map<std::string, ClassInfo> class_db;

struct GDExample : Object {
    double amplitude = 10.0, time_passed = 0.0, y = 0.0;
    void set_amplitude(double a) { amplitude = a; }
    double get_amplitude() const { return amplitude; }
    void process(double dt) { time_passed += dt; y = amplitude * std::sin(time_passed * 2.0); }

    static void bind_methods() {   // what _bind_methods + ADD_PROPERTY record
        auto& c = class_db["GDExample"];
        c.methods["set_amplitude"] = [](Object* o, double v) { static_cast<GDExample*>(o)->set_amplitude(v); return 0.0; };
        c.methods["get_amplitude"] = [](Object* o, double) { return static_cast<GDExample*>(o)->get_amplitude(); };
        c.methods["_process"] = [](Object* o, double dt) { auto* g = static_cast<GDExample*>(o); g->process(dt); return g->y; };
        c.properties["amplitude"] = {"set_amplitude", "get_amplitude", 0.0, 20.0};
    }
};

// What the inspector or `node.amplitude = 25` in GDScript does: look up the property, clamp to the hint, call the setter.
void set_property(Object* o, const std::string& cls, const std::string& name, double value) {
    auto& p = class_db[cls].properties.at(name);
    double v = std::fmin(std::fmax(value, p.min), p.max);
    class_db[cls].methods.at(p.setter)(o, v);
    std::printf("set %s = %.1f (clamped from %.1f by the range hint)\n", name.c_str(), v, value);
}

int main() {
    GDExample::bind_methods();     // GDREGISTER_CLASS(GDExample) during scene initialization
    GDExample node;
    set_property(&node, "GDExample", "amplitude", 25);
    std::printf("get_amplitude() -> %.1f\n", class_db["GDExample"].methods["get_amplitude"](&node, 0));
    for (int frame = 1; frame <= 3; frame++)
        std::printf("frame %d: y = %.3f\n", frame, class_db["GDExample"].methods["_process"](&node, 1.0 / 60));
}
set amplitude = 20.0 (clamped from 25.0 by the range hint)
get_amplitude() -> 20.0
frame 1: y = 0.667
frame 2: y = 1.332
frame 3: y = 1.997

(In the inspector, the range hint limits the slider; this model clamps every assignment to keep the example small.)

The .gdextension file and building

Godot finds the library through a small text file inside the project:

ini
; project/bin/gdexample.gdextension
[configuration]
entry_symbol = "example_library_init"
compatibility_minimum = "4.1"
reloadable = true

[libraries]
linux.debug.x86_64 = "./libgdexample.linux.template_debug.x86_64.so"
linux.release.x86_64 = "./libgdexample.linux.template_release.x86_64.so"
windows.debug.x86_64 = "./libgdexample.windows.template_debug.x86_64.dll"
windows.release.x86_64 = "./libgdexample.windows.template_release.x86_64.dll"
macos.debug = "./libgdexample.macos.template_debug.framework"
macos.release = "./libgdexample.macos.template_release.framework"
  • entry_symbol is the extern "C" function above.
  • compatibility_minimum stops older Godot versions from loading the library.
  • reloadable = true lets the editor reload the library after you rebuild (debug builds), so you don't have to restart the editor each time.
  • On export, Godot copies only the library for the target platform.

Build with SCons (the build tool Godot itself uses), from the folder with the SConstruct:

bash
git submodule add -b 4.3 https://github.com/godotengine/godot-cpp
scons platform=linux                          # debug build for the editor
scons platform=windows target=template_release   # optimised build for exported games

CMake support exists in godot-cpp as well, and the godot-cpp-template repository on GitHub is a ready-made starting point with CI that builds for every desktop platform.

GDExtension vs engine modules vs C#

GDExtension Engine module C#
Needs a custom engine build no yes (recompile Godot) no, but needs the .NET editor build
Language C++ (Rust, Swift via community bindings) C++ C#
Distribution drop the library + .gdextension into a project, or the AssetLib ship your own engine binaries NuGet + scripts
Typical use fast addons and library wrappers deep engine changes gameplay code

LimboAI, for example, ships both as a module and as a GDExtension, see AssetLib & Addons.

Test yourself

What does _bind_methods() do in a GDExtension class?

  1. Compiles GDScript
  2. Registers the class's methods, properties and signals with ClassDB so scripts and the editor can use them
  3. Binds keyboard keys
  4. Loads the shared library

Which godot-cpp branch should you build against?

  1. Always master
  2. The one matching the oldest Godot version you want to support
  3. Any 3.x branch
  4. It doesn't matter

What tells Godot which library file to load for each platform?

  1. project.godot
  2. The .gdextension file's [libraries] section
  3. export_presets.cfg
  4. The SConstruct file