Saturday, August 29, 2026

A strong case for C++ and Julia combination - my exploration continues - developing a PID controller using this approach using jluna...

 For a simple simulation or educational demonstration, we can do all of these in Julia. But in real-world applications, it's better to keep the hardware interfacing part written in C++ and the visualization part in Julia. This is a pretty common pattern (Python frontend + C++ backend, MATLAB + generated C, etc.), just with Julia instead of Python/MATLAB.

Below are some of the rational points when this tango of C++ and Julia is a good choice.

  • Real controller needs C++ strengths: If the “main controller” runs in a hard/soft real-time loop, on embedded hardware, interfaces with drivers/sensors/actuators (serial, CAN, ROS, etc.), or must meet strict latency/determinism guarantees, C++ (or C) is the conventional and safer choice. Julia’s GC, JIT compilation, and runtime make hard real-time harder (though there is recent work deploying Julia controllers on platforms like Raspberry Pi + PX4 or even microcontrollers).
  • Julia for the interactive layer: Julia excels at numerical work, control-theory tooling (ControlSystems.jl, DiscretePIDs.jl, ModelingToolkit, Dyad/JuliaSim control packages with PID autotuning), and modern interactive visualization (Makie/GLMakie with sliders, Observables, live plots of step responses, Bode/Nyquist, time series, etc.). Building a nice desktop or web-ish dashboard with live parameter sliders and plots is straightforward and productive in Julia.
  • Clean separation of concerns: Frontend (visualization + interactive tuning of
    K_p, K_i, K_d, etc.) stays in a high-level language good at maths and plotting; the performance-/hardware-critical loop stays in C++. Communication can be via sockets, shared memory, ZeroMQ, files, or (better) a thin C API + ccall / CxxWrap.jl / jluna-style interop. 

  • Finally, it may look like the following...



    Stage 0 : Verifying the basic configuration...







    The C++ side: Building the physical model

    The C++ implementation is divided into three major components.

    1. PID Controller

    The PID class implements the familiar proportional, integral and derivative control mechanism.

    The controller receives:

    • A desired position, or setpoint

    • The measured position of the system

    • The simulation time step

    It calculates the control force using the accumulated error, the current error and the rate of change of error.

    The essential control equation is:

    $$ u(t) = K_p e(t) + K_i \int e(t)\,dt + K_d \frac{de(t)}{dt} $$

    The implementation maintains the integral and previous error internally. This means that the controller has state, just as a real controller does.

    2. Plant

    The Plant class represents a simple mass-spring-damper system.

    Its physical model is based on Newton's second law:

    [
    \[ m\ddot{x} + c\dot{x} + kx = F \]
    ]

    where:

    • (m) is mass

    • (c) is damping

    • (k) is spring stiffness

    • (F) is the applied force

    The plant calculates acceleration from the net force and updates its velocity and position using semi-implicit Euler integration.

    This is a small but important step. We are no longer simply calculating a mathematical expression; we are simulating the evolution of a physical system over time.

    3. Simulation

    The Simulation class brings the controller and plant together.

    At every time step:

    1. The plant's current position is measured.

    2. The PID controller calculates the required force.

    3. The force is applied to the plant.

    4. The plant advances to its next state.

    5. The simulation returns position, velocity, force and error.

    The entire control loop is encapsulated in C++.

    This separation of responsibilities makes the implementation easier to understand, maintain and extend.

    Bringing Julia into the picture

    The next challenge was to make this C++ simulation accessible from Julia.

    I used jluna, a C++–Julia interoperability library, to establish the bridge.

    Rather than exposing the entire C++ object model directly, I created a small set of functions that Julia can call.

    For example, the C++ side provides functions for creating a PID controller, updating it, resetting it and deleting it.

    The simulation has a similar interface:

    Simulation(kp, ki, kd, mass, damping, stiffness)
    
    sim_step(sim, setpoint, dt)

    The Julia code does not need to know how the C++ classes are implemented internally.

    It simply creates a simulation, advances it and receives numerical results.

    This is an important architectural decision. The bridge exposes the functionality that Julia needs without unnecessarily exposing the internal implementation.

    Studying different PID responses

    I then extended the program to investigate how different PID gains affect the response of the system.

    Three sets of controller parameters were selected.

    Underdamped response

    run_regime(18.0, 2.0, 0.2)

    A relatively low derivative gain produces an oscillatory response in this experiment.

    The plant approaches the target position, overshoots it and oscillates before settling.

    Fast settling response

    run_regime(18.0, 4.0, 8.5)

    This parameter set produces a response intended to demonstrate a faster, more balanced approach to the setpoint with reduced overshoot.

    It is labelled as the critically damped response in the experiment. Strictly speaking, critical damping is a mathematical condition, and the actual response of a PID-controlled system depends on the complete closed-loop dynamics. The label here describes the intended response regime rather than a formally verified critical-damping condition.

    Overdamped response

    run_regime(18.0, 2.0, 22.0)

    A higher derivative gain produces a more sluggish response in this experiment, with a slower approach to the target.

    The three experiments illustrate an important engineering lesson: controller tuning is not simply about increasing gains. The objective is to find a suitable balance between speed, stability and overshoot.

    Julia takes over the visualization

    After running the simulations, Julia writes the collected data to a CSV file.

    The plotting script then uses Plots.jl to generate four figures:

    1. The underdamped response

    2. The fast-settling response

    3. The overdamped response

    4. A combined comparison of all three trajectories

    The combined graph is particularly useful because it allows us to compare the response curves against the same setpoint.

    The visualization is generated by Julia, but the underlying physical simulation is executed by C++.

    This is where the two languages complement each other rather than compete with each other.

    Why this combination makes sense

    C++ gives us control over the structure and implementation of the simulation.

    We can use classes, encapsulation, modern C++ features and efficient numerical computation to build the model.

    Julia gives us a convenient environment for experimentation.

    We can change parameters, run multiple simulations, collect data, perform numerical analysis and generate plots without rewriting the simulation engine.

    For scientific computing, this separation can be extremely useful.

    A simulation engine written in C++ can remain stable while the experimental environment evolves rapidly in Julia.

    The same approach could be extended to:

    • Robotic arm control

    • Vehicle suspension simulation

    • Rocket trajectory control

    • Thermal systems

    • Electrical circuits

    • Fluid simulation

    • Numerical optimization

                        

    Source Code

    Main.cpp

    #include "PID.hpp"
    #include "Plant.hpp"
    #include "Simulation.hpp"
    #include <jluna.hpp>
    #include <iostream>
    #include <string>
    #include <vector>
    #include <unordered_map>
    #include <mutex>
    #include <stdexcept>

    using namespace jluna;

    static std::unordered_map<Int64, PID*> g_pids;
    static std::unordered_map<Int64, Simulation*> g_sims;
    static std::mutex g_mutex;
    static Int64 g_next_id = 1;
    static Int64 g_next_sim_id = 1;

    static Int64 register_pid(PID* p)
    {
        std::lock_guard lock(g_mutex);
        Int64 id = g_next_id++;
        g_pids[id] = p;
        return id;
    }

    static PID* get_pid(Int64 id)
    {
        std::lock_guard lock(g_mutex);
        auto it = g_pids.find(id);
        if (it == g_pids.end())
            throw std::runtime_error("invalid PID handle");
        return it->second;
    }

    static void erase_pid(Int64 id)
    {
        std::lock_guard lock(g_mutex);
        auto it = g_pids.find(id);
        if (it != g_pids.end()) {
            delete it->second;
            g_pids.erase(it);
        }
    }

    static Int64 register_sim(Simulation* sim)
    {
        std::lock_guard lock(g_mutex);
        Int64 id = g_next_sim_id++;
        g_sims[id] = sim;
        return id;
    }

    static Simulation* get_sim(Int64 id)
    {
        std::lock_guard lock(g_mutex);
        auto it = g_sims.find(id);
        if (it == g_sims.end())
            throw std::runtime_error("invalid Simulation handle");
        return it->second;
    }

    static void erase_sim(Int64 id)
    {
        std::lock_guard lock(g_mutex);
        auto it = g_sims.find(id);
        if (it != g_sims.end()) {
            delete it->second;
            g_sims.erase(it);
        }
    }

    int main()
    {
        try {
            const std::string jluna_so =
                "/home/som/Workspace/C++/AdvancedC++20/CPP-Julia-Bridge/PID_CPP_Julia/third_party/jluna/install/libjluna.so";
            const std::string julia_bindir =
                "/home/som/.julia/juliaup/julia-1.10.10+0.x64.linux.gnu/bin";
            const std::string julia_image =
                "/home/som/.julia/juliaup/julia-1.10.10+0.x64.linux.gnu/lib/julia/sys.so";

            initialize(1, false, jluna_so, julia_bindir, julia_image);

            // ---- PID bindings ----
            Main.create_or_assign("pid_create",
                as_julia_function<Int64(std::vector<double>)>(
                    [](std::vector<double> gains) -> Int64
                    {
                        if (gains.size() != 3)
                            throw std::runtime_error("pid_create expects [kp, ki, kd]");
                        return register_pid(new PID(gains[0], gains[1], gains[2]));
                    }));

            Main.create_or_assign("pid_update_aux",
                as_julia_function<double(Int64, std::vector<double>)>(
                    [](Int64 id, std::vector<double> v) -> double
                    {
                        if (v.size() != 3)
                            throw std::runtime_error("pid_update expects [sp, meas, dt]");
                        return get_pid(id)->update(v[0], v[1], v[2]);
                    }));

            Main.create_or_assign("pid_reset",
                as_julia_function<void(Int64)>(
                    [](Int64 id) -> void { get_pid(id)->reset(); }));

            Main.create_or_assign("pid_delete",
                as_julia_function<void(Int64)>(
                    [](Int64 id) -> void { erase_pid(id); }));

            // ---- Simulation bindings ----
            Main.create_or_assign("sim_create_aux",
                as_julia_function<Int64(std::vector<double>)>(
                    [](std::vector<double> p) -> Int64
                    {
                        if (p.size() != 6)
                            throw std::runtime_error("sim_create expects 6 parameters");
                        auto* sim = new Simulation(p[0], p[1], p[2], p[3], p[4], p[5]);
                        return register_sim(sim);
                    }));

            Main.create_or_assign("sim_step_aux",
                as_julia_function<std::vector<double>(Int64, std::vector<double>)>(
                    [](Int64 id, std::vector<double> p) -> std::vector<double>
                    {
                        if (p.size() != 2)
                            throw std::runtime_error("sim_step expects [setpoint, dt]");
                        return get_sim(id)->step(p[0], p[1]);
                    }));

            Main.create_or_assign("sim_reset",
                as_julia_function<void(Int64)>(
                    [](Int64 id) -> void { get_sim(id)->reset(); }));

            Main.create_or_assign("sim_delete",
                as_julia_function<void(Int64)>(
                    [](Int64 id) -> void { erase_sim(id); }));

            // ---- Julia-friendly wrappers ----
            Main.safe_eval(R"(
                PID(kp, ki, kd) = pid_create(Float64[kp, ki, kd])
                pid_update(id, sp, meas, dt) = pid_update_aux(id, Float64[sp, meas, dt])

                Simulation(kp, ki, kd, mass, damping, stiffness) =
                    sim_create_aux(Float64[kp, ki, kd, mass, damping, stiffness])
                sim_step(id, setpoint, dt) =
                    sim_step_aux(id, Float64[setpoint, dt])
            )");

            // ---- PID Self-test ----
            Main.safe_eval(R"(
                p = PID(1.0, 0.1, 0.05)
                println("handle = ", p, "  typeof = ", typeof(p))
                println("update = ", pid_update(p, 10.0, 0.0, 0.01))
                pid_reset(p)
                pid_delete(p)
                println("PID bridge OK")
            )");

            // ---- Julia-controlled simulation ----
            Main.safe_eval(R"(
                println("\nJulia-controlled simulation:")

                # Higher kp (15.0) + lower damping (0.3) + 4.0 seconds (400 steps)
    sim = Simulation(15.0, 0.5, 0.0, 1.0, 0.3, 2.0)

    setpoint = 1.0
    dt = 0.01
    steps = 400

                times = Float64[]
                positions = Float64[]
                velocities = Float64[]
                forces = Float64[]
                errors = Float64[]

                for i in 1:steps
                    result = sim_step(sim, setpoint, dt)

                    push!(times, i * dt)
                    push!(positions, result[1])
                    push!(velocities, result[2])
                    push!(forces, result[3])
                    push!(errors, result[4])

                    if i % 10 == 0
                        println(
                            "t = ", times[end],
                            " x = ", positions[end],
                            " v = ", velocities[end],
                            " force = ", forces[end],
                            " error = ", errors[end]
                        )
                    end
                end

                println("Julia simulation completed.")
                println("Collected ", length(times), " samples.")
                flush(stdout)

                sim_delete(sim)
            )");

            // ---- Blog Post Visualization: Underdamped, Critically Damped (Steady-State), and Overdamped
            Main.safe_eval(R"julia(
                println("\nRunning PID damping regime simulations for blog post...")

                function run_regime(kp, ki, kd; setpoint=1.0, dt=0.01, steps=800)
                    sim = Simulation(kp, ki, kd, 1.0, 0.5, 2.0)
                    t = Vector{Float64}(undef, steps)
                    x = Vector{Float64}(undef, steps)
                    for i in 1:steps
                        res = sim_step(sim, setpoint, dt)
                        t[i] = i * dt
                        x[i] = res[1]
                    end
                    sim_delete(sim)
                    return t, x
                end

                # 1. Underdamped (low Kd -> oscillatory decay)
                t, x_under = run_regime(18.0, 2.0, 0.2)

                # 2. Critically Damped / Fast Steady-State (balanced Kd -> fast settle, no overshoot)
                _, x_crit  = run_regime(18.0, 4.0, 8.5)

                # 3. Overdamped (high Kd -> sluggish approach, no overshoot)
                _, x_over  = run_regime(18.0, 2.0, 22.0)

                using DelimitedFiles
                writedlm("blog_damping_data.csv", hcat(t, x_under, x_crit, x_over), ',')

                plot_script = """
                    ENV["GKSwstype"] = "100"
                    using DelimitedFiles, Plots

                    d = readdlm("blog_damping_data.csv", ',')
                    t, x_under, x_crit, x_over = d[:, 1], d[:, 2], d[:, 3], d[:, 4]
                    sp = 1.0

                    # Common styling for crisp blog figures (high DPI)
                    base_kwargs = (
                        xlabel = "Time (s)",
                        ylabel = "Position x(t)",
                        xlims = (0, 8.0),
                        ylims = (0, 1.85),
                        grid = true,
                        minorgrid = true,
                        framestyle = :box,
                        dpi = 300,
                        size = (850, 480)
                    )

                    # --- Graph 1: Underdamped Response ---
                    p_under = plot(t, x_under;
                        title = "1. Underdamped PID Response (Kp=18, Ki=2, Kd=0.2)",
                        label = "Underdamped Trajectory",
                        color = :royalblue,
                        linewidth = 2.5,
                        base_kwargs...
                    )
                    hline!(p_under, [sp], label = "Steady-State Setpoint (1.0)", linestyle = :dash, color = :black)
                    savefig(p_under, "blog_1_underdamped.png")

                    # --- Graph 2: Critically Damped / Steady-State Response ---
                    p_crit = plot(t, x_crit;
                        title = "2. Critically Damped / Steady-State Response (Kp=18, Ki=4, Kd=8.5)",
                        label = "Critically Damped Trajectory",
                        color = :forestgreen,
                        linewidth = 2.5,
                        base_kwargs...
                    )
                    hline!(p_crit, [sp], label = "Steady-State Setpoint (1.0)", linestyle = :dash, color = :black)
                    savefig(p_crit, "blog_2_steadystate_critically_damped.png")

                    # --- Graph 3: Overdamped Response ---
                    p_over = plot(t, x_over;
                        title = "3. Overdamped PID Response (Kp=18, Ki=2, Kd=22.0)",
                        label = "Overdamped Trajectory",
                        color = :darkorange,
                        linewidth = 2.5,
                        base_kwargs...
                    )
                    hline!(p_over, [sp], label = "Steady-State Setpoint (1.0)", linestyle = :dash, color = :black)
                    savefig(p_over, "blog_3_overdamped.png")

                    # --- Graph 4: Combined Blog Hero Comparison ---
                    p_all = plot(t, x_under;
                        title = "PID Control Damping Regimes (C++ Simulation + Julia Plots)",
                        label = "Underdamped (Kd = 0.2)",
                        color = :royalblue,
                        linewidth = 2.5,
                        base_kwargs...
                    )
                    plot!(p_all, t, x_crit, label = "Critically Damped / Optimal Steady-State (Kd = 8.5)", color = :forestgreen, linewidth = 2.5)
                    plot!(p_all, t, x_over, label = "Overdamped (Kd = 22.0)", color = :darkorange, linewidth = 2.5, linestyle = :dashdot)
                    hline!(p_all, [sp], label = "Target Setpoint (1.0)", linestyle = :dash, color = :black)
                    savefig(p_all, "blog_4_combined_comparison.png")

                    println("Generated all 4 blog PNGs in: ", pwd())
                """

                cmd = addenv(`$(Base.julia_cmd()) -e $plot_script`, "LD_LIBRARY_PATH" => "")
                run(cmd)
                flush(stdout)
            )julia");
        }
        catch (const std::exception& e) {
            std::cerr << "Julia/jluna error: " << e.what() << std::endl;
        }

        // ---- Pure C++ Plant verification ----
        Plant plant(1.0, 0.5, 2.0);

        std::cout << "\nPlant test:\n";

        for (int i = 0; i < 10; ++i)
        {
            plant.update(10.0, 0.01);

            std::cout << "t = " << (i + 1) * 0.01
                      << "  x = " << plant.position()
                      << "  v = " << plant.velocity()
                      << std::endl;
        }

        return 0;
    }
             

    PID.hpp

    #pragma once

    class PID {
    public:
        PID(double kp, double ki, double kd);

        double update(double setpoint,
                      double measurement,
                      double dt);

        void reset();

    private:
        double kp_;
        double ki_;
        double kd_;

        double integral_;
        double previous_error_;
    };

    PID.cpp


    #include "PID.hpp"

    PID::PID(double kp, double ki, double kd)
        : kp_(kp),
          ki_(ki),
          kd_(kd),
          integral_(0.0),
          previous_error_(0.0)
    {
    }

    double PID::update(double setpoint,
                       double measurement,
                       double dt)
    {
        const double error = setpoint - measurement;

        integral_ += error * dt;

        const double derivative =
            (error - previous_error_) / dt;

        previous_error_ = error;

        return kp_ * error
             + ki_ * integral_
             + kd_ * derivative;
    }

    void PID::reset()
    {
        integral_ = 0.0;
        previous_error_ = 0.0;
    }
       

    Plant.hpp


    #pragma once

    class Plant {
    public:
        Plant(double mass, double damping, double stiffness);

        void update(double force, double dt);
        void reset();

        double position() const;
        double velocity() const;

    private:
        double mass_;
        double damping_;
        double stiffness_;

        double position_;
        double velocity_;
    };

    Plant.cpp


    #include "Plant.hpp"
    #include <stdexcept>

    Plant::Plant(double mass, double damping, double stiffness)
        : mass_(mass),
          damping_(damping),
          stiffness_(stiffness),
          position_(0.0),
          velocity_(0.0)
    {
        if (mass <= 0.0)
            throw std::invalid_argument("Mass must be positive");

        if (damping < 0.0 || stiffness < 0.0)
            throw std::invalid_argument(
                "Damping and stiffness cannot be negative");
    }

    void Plant::update(double force, double dt)
    {
        if (dt <= 0.0)
            throw std::invalid_argument("dt must be positive");

        // Newton's second law:
        // m * acceleration = force - damping - spring force

        const double spring_force =
            stiffness_ * position_;

        const double damping_force =
            damping_ * velocity_;

        const double net_force =
            force - spring_force - damping_force;

        const double acceleration =
            net_force / mass_;

        // Semi-implicit Euler integration
        velocity_ += acceleration * dt;
        position_ += velocity_ * dt;
    }

    void Plant::reset()
    {
        position_ = 0.0;
        velocity_ = 0.0;
    }

    double Plant::position() const
    {
        return position_;
    }

    double Plant::velocity() const
    {
        return velocity_;
    }

    Simulation.hpp


    #pragma once

    #include "PID.hpp"
    #include "Plant.hpp"

    #include <vector>

    class Simulation {
    public:
        Simulation(
            double kp,
            double ki,
            double kd,
            double mass,
            double damping,
            double stiffness
        );

        std::vector<double> step(
            double setpoint,
            double dt
        );

        void reset();

    private:
        PID pid_;
        Plant plant_;
    };

    Simulation.cpp


    #include "Simulation.hpp"

    Simulation::Simulation(
        double kp,
        double ki,
        double kd,
        double mass,
        double damping,
        double stiffness
    )
        : pid_(kp, ki, kd),
          plant_(mass, damping, stiffness)
    {
    }

    std::vector<double> Simulation::step(
        double setpoint,
        double dt
    )
    {
        // Measure the current plant position
        const double position = plant_.position();

        // Calculate control force
        const double force =
            pid_.update(setpoint, position, dt);

        // Apply force to the physical plant
        plant_.update(force, dt);

        // Return updated simulation data
        return {
            plant_.position(),
            plant_.velocity(),
            force,
            setpoint - position
        };
    }

    void Simulation::reset()
    {
        pid_.reset();
        plant_.reset();
    }


    CMakeLists.txt

    cmake_minimum_required(VERSION 3.20)

    project(PID_CPP_Julia
        VERSION 1.0
        LANGUAGES CXX
    )

    # --------------------------------------------------
    # C++ Standard (jluna requires C++20)
    # --------------------------------------------------
    set(CMAKE_CXX_STANDARD 20)
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    set(CMAKE_CXX_EXTENSIONS OFF)

    # --------------------------------------------------
    # Julia Discovery
    # --------------------------------------------------
    execute_process(
        COMMAND julia -e "print(Sys.BINDIR)"
        OUTPUT_VARIABLE JULIA_BINDIR
        OUTPUT_STRIP_TRAILING_WHITESPACE
    )

    if(NOT JULIA_BINDIR)
        message(FATAL_ERROR "Julia executable not found in PATH.")
    endif()

    get_filename_component(JULIA_PREFIX "${JULIA_BINDIR}" DIRECTORY)
    set(JULIA_INCLUDE_DIR "${JULIA_PREFIX}/include/julia")
    set(JULIA_LIB_DIR     "${JULIA_PREFIX}/lib")

    message(STATUS "Julia BINDIR      : ${JULIA_BINDIR}")
    message(STATUS "Julia PREFIX      : ${JULIA_PREFIX}")
    message(STATUS "Julia INCLUDE_DIR : ${JULIA_INCLUDE_DIR}")
    message(STATUS "Julia LIB_DIR     : ${JULIA_LIB_DIR}")

    # --------------------------------------------------
    # jluna (Pre-built in third_party/jluna/install)
    # --------------------------------------------------
    set(JLUNA_ROOT    ${CMAKE_CURRENT_SOURCE_DIR}/third_party/jluna)
    set(JLUNA_LIB_DIR ${JLUNA_ROOT}/install)

    find_library(JLUNA_LIB
        NAMES jluna
        PATHS ${JLUNA_LIB_DIR}
        NO_DEFAULT_PATH
        REQUIRED
    )

    # Locate jluna.jl runtime script
    if(EXISTS "${JLUNA_ROOT}/jluna.jl")
        set(JLUNA_JL_PATH "${JLUNA_ROOT}/jluna.jl")
    elseif(EXISTS "${JLUNA_ROOT}/jluna/jluna.jl")
        set(JLUNA_JL_PATH "${JLUNA_ROOT}/jluna/jluna.jl")
    endif()

    message(STATUS "jluna library     : ${JLUNA_LIB}")
    message(STATUS "jluna script      : ${JLUNA_JL_PATH}")

    # --------------------------------------------------
    # Executable Configuration
    # --------------------------------------------------
    add_executable(PID_CPP_Julia
        cpp/main.cpp
        cpp/PID.cpp
        cpp/Plant.cpp
        cpp/Simulation.cpp
    )

    target_include_directories(PID_CPP_Julia PRIVATE
        cpp
        ${JLUNA_ROOT}
        ${JLUNA_ROOT}/include
        ${JLUNA_ROOT}/install/include
        ${JULIA_INCLUDE_DIR}
    )

    # Pass script path to C++ macro
    target_compile_definitions(PID_CPP_Julia PRIVATE
        JLUNA_JL_PATH=${JLUNA_JL_PATH}
    )

    target_link_directories(PID_CPP_Julia PRIVATE
        ${JULIA_LIB_DIR}
        ${JLUNA_LIB_DIR}
    )

    target_link_libraries(PID_CPP_Julia PRIVATE
        ${JLUNA_LIB}
        julia
        dl
        pthread
        m
        rt
    )

    # Set RPATH so executable finds libjulia.so and libjluna.so at runtime
    set_target_properties(PID_CPP_Julia PROPERTIES
        BUILD_RPATH   "${JULIA_LIB_DIR};${JLUNA_LIB_DIR}"
        INSTALL_RPATH "${JULIA_LIB_DIR};${JLUNA_LIB_DIR}"
    )

    target_compile_features(PID_CPP_Julia PRIVATE cxx_std_20)

    Friday, August 28, 2026

    When My Son Inspired Me to explore a Bridge Between C++ and Julia...

    Here's the video of a very simple program in which the Julia runtime is embedded inside C++.




    Some programming projects begin with a problem.

    Some begin with curiosity.

    And some begin with a conversation between a father and his son.

    This one began with my son.

    My son has been exploring programming, graphics, simulation and the fascinating world of computers. As I watched him move from one technology to another—C++, Python, Java, graphics and simulation—I found myself revisiting areas of computer science that I had not touched seriously for years.

    And somehow, that journey brought me back to C++.

    But not just C++.

    It led me to Julia.

    And then came an interesting question:

    What if C++ and Julia could work together inside the same application?

    That question eventually led me to jluna.

    Why C++ and Julia?

    C++ and Julia come from rather different programming traditions.

    C++ is the language I naturally associate with systems programming, performance, memory control, large-scale simulation and real-time applications.

    Julia, on the other hand, feels almost purpose-built for scientific computing.

    It combines a high-level mathematical syntax with impressive numerical performance.

    For someone interested in physics simulation, control systems, computational science and graphics, the combination is rather attractive.

    Imagine having the core simulation or controller in C++, while using Julia for:

    • numerical experimentation

    • visualization

    • plotting

    • interactive parameter tuning

    • rapid prototyping

    • scientific analysis

    That immediately opens up some interesting possibilities.

    The idea of a bridge

    Calling C++ from Julia is already possible through several mechanisms.

    But I was particularly interested in the opposite direction:

    Embedding Julia inside a C++ application.

    The architecture I had in mind was something like this:

                     C++ Application
                           │
                  ┌────────┴────────┐
                  │                 │
            Simulation /        Julia Runtime
            Controller              │
                  │          ┌───────┴───────┐
                  │          │ Visualization │
                  │          │ Experimentation│
                  │          │ Data Analysis │
                  │          └───────────────┘
                  │
                  └────────── jluna ──────────┘
    

    This is where jluna became interesting.

    Rather than treating Julia as a completely separate program, jluna provides a C++ interface for interacting with an embedded Julia runtime.

    And suddenly, the idea of a C++ program calling Julia code didn't feel so exotic.

    My first jluna experiment

    I decided not to start with a complicated application.

    No physics engine.

    No PID controller.

    No graphics.

    Just a tiny experiment:

    Can a C++ program start Julia and execute Julia code?

    That simple question became the first milestone.

    I created a small C++/CMake project and started working through the mechanics of embedding Julia.

    There were several pieces to understand:

    • locating the Julia installation

    • configuring CMake

    • linking the C++ application

    • initializing the Julia runtime

    • evaluating Julia expressions

    • passing values between C++ and Julia

    The interesting part wasn't simply getting the first program to run.

    It was understanding where the boundary between the two languages actually lies.

    Crossing the language boundary

    Once you start thinking about C++ and Julia as two parts of the same application, a more interesting question appears:

    What should belong to C++, and what should belong to Julia?

    For example, consider a PID controller.

    The controller itself could live in C++:

    Sensor
       ↓
    C++ PID Controller
       ↓
    Actuator
    

    But during development, I might want Julia to provide:

                 Julia
                   │
           ┌───────┼────────┐
           ↓       ↓        ↓
         Plot     Slider   Analysis
           │       │        │
           └───────┼────────┘
                   ↓
                 C++
              PID Controller
    

    Julia could change Kp, Ki and Kd interactively.

    The C++ controller could continue doing the real work.

    Julia could plot the response in real time.

    Now the bridge becomes much more than a programming curiosity.

    It becomes an architecture for experimentation.

    The father-son effect

    There is something amusing about this journey.

    I started exploring C++ and Julia because my son was exploring programming and simulation.

    Instead of simply teaching him something, I found myself learning something new as well.

    That is one of the unexpected pleasures of being a parent.

    Sometimes we imagine that we are introducing our children to technology.

    But they quietly introduce us to new technology too.

    A question from a young programmer can send a father down a rabbit hole involving CMake, compilers, ABI compatibility, Julia's runtime, C++ templates and foreign-function interfaces.

    And suddenly it is midnight and you're reading documentation about jluna.

    Why this exploration matters to me

    I'm not approaching jluna because I need another language binding for a production application.

    I'm exploring it because it sits at an interesting intersection of several things I enjoy:

    C++ + numerical computing + simulation + visualization + experimentation.

    C++ gives me control and performance.

    Julia gives me an expressive scientific environment.

    And jluna provides the bridge.

    The more I explore this combination, the more interesting the possibilities become.

    Perhaps the final project will be a PID controller.

    Perhaps a physics simulation.

    Perhaps something involving graphics.

    Or perhaps it will simply remain another enjoyable rabbit hole in my never-ending journey through computer science.

    But that is perfectly fine.

    Because sometimes the best projects aren't the ones that solve a business problem.

    They are the ones that make you curious again.

    And this particular curiosity started with my son.

    **He was exploring programming.

    I followed him down the rabbit hole.

    And somewhere along the way, we discovered a bridge between C++ and Julia.**



    Monday, August 3, 2026

    From Eclipse CDT to Zed + clangd — The Exploratory Engineer in Me Is Still Alive...



    I recently started moving from Eclipse CDT to Zed + clangd for my C++ development.

    On the surface, it is just an IDE change.

    For me, it is something more.

    Eclipse CDT has been a trusted companion for years. Projects, indexing, debugging, builds, refactoring—everything became familiar. And that familiarity is comfortable.

    But there is a danger in becoming too comfortable with the tools. Development becomes routine. We loose the power of curiosity.

    And then...

    Things that had become invisible are interesting again.

    Look at the image, which is clangd's compile_commands.json.

    clangd needs to know this information.

    Which compiler?

    Which C++ standard?

    Which include directories?

    Which preprocessor definitions?

    Which compilation flags?

    Once I started looking at it this way, clangd stopped feeling like some mysterious IDE feature.

    It became what it really is:

    a tool that needs an accurate model of how the compiler sees the source code.

    That shift in perspective makes troubleshooting much easier.

    How does clangd understand my project?
    What exactly does CMake generate?
    How does the debugger interact with my program?
    How much of an IDE do I actually need?

    These are not merely editor questions. They are engineering questions.

    And perhaps that is what I enjoy most.


    As engineers gain experience, there is a risk of becoming operators of familiar systems rather than explorers of new ones.

    I don't want that.

    The move from Eclipse to Zed is therefore not really about:

    Eclipse → Zed + clangd




    It is about:

    Routine → Exploration

    Familiarity → Curiosity

    "This is how I always do it" → "What happens if I try this?"

    Why This Experiment Is Interesting to Me

    I have always enjoyed understanding what happens underneath the abstraction.

    That is probably why I keep moving between areas such as:

    • C++
    • Java
    • Python
    • Linux
    • OpenGL
    • CUDA
    • OpenFOAM
    • ParaView
    • Julia
    • Blender
    • numerical simulation
    • computer graphics
    • design patterns

    There is a common thread running through all of them.

    I don't just want to use the software.

    I want to understand how the machinery works.

    Moving from Eclipse CDT to Zed + clangd is another small expression of the same instinct.

    The editor itself becomes less important.

    The interesting part is understanding the ecosystem around it.



    The tools will keep changing—C++, compilers, build systems, editors, AI, GPUs, simulation frameworks.

    The important thing is to keep experimenting.

    Because after years of programming, discovering a new tool is nice.

    But discovering that the explorative engineer inside me is still alive—and thriving is much better.