Quantitative Development Debugging a European FX option in QuantLib C++ ...

Debugging a European FX option in QuantLib C++ with VS Code.

Debugging a European FX option in QuantLib C++ with VS Code.

Warning: This post is under construction. It is being extended beyond QuantLib debug setup and is used as a component for another post on debugging QuantLib. Content may be incomplete or subject to change.

In the previous post I explained how to compile QuantLib in debug mode. In this one, I want to close the loop with a realistic test: pricing a European FX option in C++, linking against the debug QuantLib installation, and running the code from VS Code with breakpoints and variable inspection.

The example uses QuantLib’s GarmanKohlagenProcess, which models the domestic and foreign interest rates directly for an FX option. This is a good test case because it is simple enough to run quickly but rich enough to inspect curves, volatility structures, and pricing engine internals while debugging.

Scenario and model assumptions

Assume we want to price a six-month European call on EUR, with the exchange rate quoted as EURUSD (US dollars per euro). The option gives its holder the right, but not the obligation, to buy euros at the strike in exchange for dollars.

Input Value Meaning
Spot, $S_0$ 1.1000 USD per EUR Current EURUSD exchange rate: one euro costs 1.10 US dollars.
Strike, $K$ 1.1200 USD per EUR Dollars paid for each euro if the option is exercised.
Time to expiry, $T$ 6 months Time from the valuation date to the European exercise date.
Domestic rate, $r_d$ 3.00% USD risk-free rate, with USD as the quote currency.
Foreign rate, $r_f$ 1.50% EUR risk-free rate, with EUR as the base currency.
Volatility, $\sigma$ 12.00% Annualized volatility of the EURUSD exchange rate.

How the Garman-Kohlhagen model prices the option

The Garman-Kohlhagen (G-K) model extends the Black-Scholes framework to options on exchange rates. For this EURUSD call, its value per euro of notional, expressed in US dollars, is

\[C = S_0 e^{-r_f T}\Phi(d_1) - K e^{-r_d T}\Phi(d_2), \qquad d_1 = \frac{\ln(S_0/K) + (r_d-r_f+\tfrac{1}{2}\sigma^2)T} {\sigma\sqrt{T}}, \qquad d_2 = d_1-\sigma\sqrt{T},\]

where $\Phi$ is the standard normal cumulative distribution function. The two discount factors reflect the two currencies: the foreign rate discounts the spot-currency leg, while the domestic rate discounts the strike payment. Equivalently, the model values the expected option payoff under the domestic pricing measure. The terminal payoff per euro is $\max(S_T-K,0)$, where $S_T$ is the EURUSD rate at expiry. Multiply the model value by the option’s EUR notional to obtain a total premium in USD.

G-K is not a separate pricing formula from Black-Scholes so much as its FX-specific application. When an asset is priced in a domestic currency but generates a continuous yield $q$, the Black-Scholes-Merton call formula uses $S_0e^{-qT}$ for the spot term. For a foreign currency, that yield is the foreign risk-free rate, so G-K corresponds to setting $q=r_f$ and discounting the strike at $r_d$. The zero-yield Black-Scholes special case does not capture this foreign-currency carry. Using only one rate would omit the return associated with holding the foreign currency.

The model was presented by Mark B. Garman and Steven W. Kohlhagen in their 1983 paper, “Foreign currency option values” (Garman & Kohlhagen, 1983).

In QuantLib, these assumptions map to flat domestic and foreign yield curves, a flat Black volatility surface, and a GarmanKohlagenProcess. AnalyticEuropeanEngine applies the closed-form G-K valuation to the European payoff.

Minimal project structure

You can create a small folder anywhere outside your QuantLib source tree, for example:

fx-option-debug/
├── CMakeLists.txt
├── main.cpp
└── .vscode/
    ├── tasks.json
    └── launch.json
File or folder Role
main.cpp The C++ example: it defines the market inputs, builds the EURUSD option and pricing engine, then calculates and prints the price and risk measures.
CMakeLists.txt Tells CMake how to compile main.cpp, where to find the QuantLib headers and library, and how to link the program. See Section 4: CMake configuration for the example and details.
.vscode/ Holds project-specific VS Code settings. Keeping these here means the editor can use the same build and debug setup whenever you open this project folder.
.vscode/tasks.json Defines repeatable build tasks, such as configuring CMake and compiling the executable. VS Code can run these from its task interface or automatically before debugging.
.vscode/launch.json Defines how VS Code starts the program under the debugger, including the executable path, working directory, and debugger settings. This is what makes breakpoints and variable inspection available when you press F5.

C++ code (main.cpp)

#include <ql/quantlib.hpp>
#include <iostream>
#include <iomanip>

int main() {
    using namespace QuantLib;

    Calendar calendar = TARGET();
    Date valuationDate(11, July, 2026);
    Settings::instance().evaluationDate() = valuationDate;

    // Market inputs
    const Real spot = 1.1000;
    const Real strike = 1.1200;
    const Rate rd = 0.03;   // domestic rate (USD)
    const Rate rf = 0.015;  // foreign rate (EUR)
    const Volatility vol = 0.12;

    Date maturityDate = calendar.advance(valuationDate, Period(6, Months));
    DayCounter dc = Actual365Fixed();

    Handle<Quote> spotHandle(ext::make_shared<SimpleQuote>(spot));

    Handle<YieldTermStructure> domesticCurve(
        ext::make_shared<FlatForward>(valuationDate, rd, dc));

    Handle<YieldTermStructure> foreignCurve(
        ext::make_shared<FlatForward>(valuationDate, rf, dc));

    Handle<BlackVolTermStructure> volCurve(
        ext::make_shared<BlackConstantVol>(valuationDate, calendar, vol, dc));

    ext::shared_ptr<GarmanKohlagenProcess> process =
        ext::make_shared<GarmanKohlagenProcess>(spotHandle, foreignCurve, domesticCurve, volCurve);

    ext::shared_ptr<StrikedTypePayoff> payoff =
        ext::make_shared<PlainVanillaPayoff>(Option::Call, strike);

    ext::shared_ptr<Exercise> exercise =
        ext::make_shared<EuropeanExercise>(maturityDate);

    VanillaOption option(payoff, exercise);
    option.setPricingEngine(ext::make_shared<AnalyticEuropeanEngine>(process));

    // Recommended first breakpoint for debugging in VS Code.
    const Real npv = option.NPV();

    std::cout << std::fixed << std::setprecision(6);
    std::cout << "European FX option (Call)" << std::endl;
    std::cout << "NPV   : " << npv << std::endl;
    std::cout << "Delta : " << option.delta() << std::endl;
    std::cout << "Gamma : " << option.gamma() << std::endl;
    std::cout << "Vega  : " << option.vega() << std::endl;
    std::cout << "Theta : " << option.theta() << std::endl;
    std::cout << "Rho   : " << option.rho() << std::endl;

    return 0;
}

CMake configuration (CMakeLists.txt)

CMake is a cross-platform build system generator. Rather than compile C++ code itself, it reads project instructions from CMakeLists.txt and generates native build files for tools such as Ninja or Make. Those tools then invoke the compiler and linker to turn source files into an executable.

For a small example, CMake can make the build repeatable: the source files, C++ standard, include directories, libraries, and build options are recorded once instead of being retyped in long compiler commands. The same project description can also generate build files for different supported platforms and toolchains. This is especially helpful with QuantLib, where the program must find the matching headers and library at compile and link time.

Here, the configuration declares the C++ executable, selects C++17 and Debug mode, points to the debug QuantLib installation, and links the required library. Debug builds include symbol information used by a debugger to map machine instructions back to source code. CMake does not install QuantLib or provide a compiler. Those prerequisites must already be available on the system.

cmake_minimum_required(VERSION 3.16)
project(FxOptionDebug CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_BUILD_TYPE Debug)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

add_executable(fx_option_debug main.cpp)

set(QUANTLIB_DEBUG_PREFIX "$ENV{HOME}/quantlib-debug-install")

target_include_directories(fx_option_debug PRIVATE
    ${QUANTLIB_DEBUG_PREFIX}/include)

target_link_libraries(fx_option_debug PRIVATE
    ${QUANTLIB_DEBUG_PREFIX}/lib/libQuantLib.so)

# Helpful so the executable can find libQuantLib.so at runtime.
set_target_properties(fx_option_debug PROPERTIES
    BUILD_RPATH "${QUANTLIB_DEBUG_PREFIX}/lib")

# Boost via vcpkg
find_package(Boost REQUIRED)  # add COMPONENTS if you need specific libs
target_link_libraries(fx_option_debug PRIVATE Boost::boost)

VS Code setup for debugging

The key adjustment in VS Code is to ensure the debugger launches the executable built in Debug mode and uses gdb (or lldb) with symbols available.

For VS Code to understand and automate your C++ workflow, these configuration files must be stored inside a folder named .vscode at the root of your project. In practice, tasks.json defines how the project is configured and built, launch.json defines how the debugger runs the executable, and (optionally) c_cpp_properties.json helps IntelliSense resolve includes and compile flags. Keeping them together in .vscode makes the setup portable and reproducible for anyone opening the same project.

tasks.json

This file tells VS Code which terminal commands to run before debugging. In this example, the first task configures CMake in Debug mode and the second task compiles the project. Because launch.json uses preLaunchTask, pressing F5 can trigger a full configure+build cycle automatically, so your debug session always runs the latest binary.

Important: the flag -DCMAKE_TOOLCHAIN_FILE=<path-to-your-vcpkg-folder>/vcpkg/scripts/buildsystems/vcpkg.cmake is only a template and must be adjusted to your own local vcpkg location. Replace <path-to-your-vcpkg-folder> with your real path, for example /home/your-user/vcpkg on Linux.

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Configure CMake (Debug)",
      "type": "shell",
      "command": "cmake",
      "args": [
        "-S", ".",
        "-B", "build",
        "-DCMAKE_BUILD_TYPE=Debug",
        "-DCMAKE_TOOLCHAIN_FILE=<path-to-your-vcpkg-folder>/vcpkg/scripts/buildsystems/vcpkg.cmake",
        "-DVCPKG_TARGET_TRIPLET=x64-linux"
      ],
      "group": "build"
    },
    {
      "label": "Build",
      "type": "shell",
      "command": "cmake",
      "args": [
        "--build", "build", "-j"
      ],
      "dependsOn": "Configure CMake (Debug)",
      "group": "build"
    }
  ]
}

If this path is wrong, CMake usually fails during configuration and find_package(Boost REQUIRED) will not resolve dependencies from vcpkg.

launch.json

This file defines how VS Code starts the debugger for your executable. While tasks.json builds the binary, launch.json controls the runtime context used by gdb/lldb: which program to start, where to run it, which environment variables to inject, and which pre-launch build task to execute.

For this QuantLib debug workflow, the most relevant parameters are:

Parameter Purpose in this configuration
program Points to the debug executable, here build/fx_option_debug.
cwd Sets the working directory used when the program runs.
preLaunchTask Builds the project before each debug run so the debugger uses the latest executable.
MIMode Selects the debugger backend. This example uses gdb on Linux.
environment Sets environment variables for the debugged process. In particular, LD_LIBRARY_PATH helps the loader find the debug libQuantLib.so under $HOME/quantlib-debug-install/lib.
setupCommands Runs debugger commands at startup. Here, it enables pretty printing for clearer object inspection.

If program or LD_LIBRARY_PATH are wrong, breakpoints may not bind correctly or the process may fail to start due to missing shared libraries.

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug FX Option (QuantLib)",
      "type": "cppdbg",
      "request": "launch",
      "program": "${workspaceFolder}/build/fx_option_debug",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [
        {
          "name": "LD_LIBRARY_PATH",
          "value": "${env:HOME}/quantlib-debug-install/lib:${env:LD_LIBRARY_PATH}"
        }
      ],
      "externalConsole": false,
      "MIMode": "gdb",
      "preLaunchTask": "Build",
      "setupCommands": [
        {
          "description": "Enable pretty printing",
          "text": "-enable-pretty-printing",
          "ignoreFailures": true
        }
      ]
    }
  ]
}

With this setup, put a breakpoint on option.NPV(), start debugging, and inspect variables such as spot, rd, rf, vol, and maturityDate.

c_cpp_properties.json

This file configures how VS Code C/C++ IntelliSense understands your project: header discovery, compiler model, standard version, and browse/index behavior. It is not the file that builds or launches debugging directly, but it is essential for accurate code navigation, auto-completion, and error squiggles while editing.

The most important parameter for this QuantLib setup is includePath. You must include "${env:HOME}/quantlib-debug-install/include", because that is where QuantLib headers were installed in the debug workflow. If this path is missing or wrong, VS Code may show false include errors even when CMake build works.

More details about the QuantLib debug folder QuantLib Debug Build post.

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "${env:HOME}/quantlib-debug-install/include"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/clang",
            "cStandard": "c17",
            "cppStandard": "c++17",
            "intelliSenseMode": "linux-clang-x64",
            "browse": {},
            "compileCommands": "${workspaceFolder}/build/compile_commands.json"
        }
    ],
    "version": 4
}

Relevant parameters to check first when something looks wrong:

Parameter What to check
includePath Include ${env:HOME}/quantlib-debug-install/include so IntelliSense can find QuantLib headers.
compilerPath Set this to the compiler used by CMake.
cppStandard Match the language standard used by the project, which is C++17 in this example.
compileCommands When the file exists and is valid, IntelliSense can use the compile flags generated by CMake.
intelliSenseMode Match the operating system, compiler, and target architecture. This example uses linux-clang-x64.

What to inspect while debugging

Below is a practical step-by-step sequence to debug this C++ example in VS Code.

  1. Open the folder containing main.cpp, CMakeLists.txt, and .vscode/.
  2. Run Run Build Task (or press F5 directly if preLaunchTask is configured).
  3. Set your first breakpoint on the line const Real npv = option.NPV();.
  4. Press F5 and select Debug FX Option (QuantLib).
  5. In the Run and Debug view, verify the program stops on your breakpoint.
  6. Use Step Over (F10) to move line by line through pricing code.
  7. Use Step Into (F11) when you want to enter QuantLib calls.
  8. Watch key variables in Variables or add them to Watch: spot, strike, rd, rf, vol, maturityDate, and npv.
  9. Open the Debug Console to evaluate expressions (for example, option.delta()).
  10. Continue (F5) to finish execution and confirm final NPV/Greeks output.

If breakpoints do not bind or the process fails to start, check these first:

  • binary is built in Debug mode,
  • program in launch.json points to the current executable,
  • LD_LIBRARY_PATH contains $HOME/quantlib-debug-install/lib,
  • symbols are available (not stripped),
  • VS Code is using the intended gdb toolchain.

Official Microsoft visual guides

This example is intentionally compact, but it is already enough to validate your full debug workflow end to end: code, model, build, runtime linking, and IDE debugging using QuantLib. Once this is stable, extending to smile surfaces, local vol, or even custom engines becomes much easier because you can inspect every layer with confidence.

Alternative: compile and run from the command line

VS Code is convenient for inspecting the calculation, but it is not required to build or run it. You can use the same CMake project from a terminal and obtain the same option value and risk measures. This is also a useful diagnostic: if the example runs from the terminal but not from VS Code, the next place to investigate is the IDE’s launch configuration rather than the pricing model.

The commands below follow the Linux setup used throughout this post. They assume that CMake, a C++17 compiler, and a build tool are available, QuantLib is installed under $HOME/quantlib-debug-install, and Boost is available through your existing vcpkg installation. No files from .vscode are needed for this route.

1. Configure the project

Open a terminal in the folder containing main.cpp and CMakeLists.txt. Replace the example vcpkg path below with the actual location of your vcpkg directory before running:

cmake -S . -B build \
  -DCMAKE_BUILD_TYPE=Debug \
  -DCMAKE_TOOLCHAIN_FILE="$HOME/vcpkg/scripts/buildsystems/vcpkg.cmake" \
  -DVCPKG_TARGET_TRIPLET=x64-linux

Configuration checks the compiler and dependencies and generates the build instructions. It does not yet compile the program. Here, -S . selects the current folder as the source directory, while -B build keeps generated files in a separate build directory. Use the same vcpkg toolchain and triplet as in the VS Code workflow. If an existing build directory was configured with a different toolchain, use a fresh directory, such as build-cli, consistently in all commands below.

2. Compile the executable

Once configuration finishes successfully, build the example:

cmake --build build --parallel 2

This compiles main.cpp and links the executable against the debug QuantLib library specified in CMakeLists.txt. The parallelism limit of two is a modest starting point. Adjust it to the resources available on your machine. After editing the C++ code, run this build command again before executing the program.

3. Run the pricing calculation

After a successful build, run:

./build/fx_option_debug

The CMake configuration above embeds a runtime search path (BUILD_RPATH) pointing to your QuantLib installation, so a separate library-path setting should not normally be necessary. If the loader reports that it cannot find libQuantLib.so, first verify the installation path. To explicitly supply that directory for this invocation, use:

LD_LIBRARY_PATH="$HOME/quantlib-debug-install/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" \
  ./build/fx_option_debug

This sets the library search path only for the program being launched and preserves any existing entries.

The output reports the call option’s NPV, delta, gamma, vega, theta, and rho. With EURUSD quoted as USD per EUR, the NPV is expressed in USD per EUR of notional, not as the premium for an entire trade. Multiply it by the EUR notional to obtain the model premium in USD. QuantLib’s vega is quoted per unit change in volatility, so multiply it by 0.01 for an approximate sensitivity to a one-percentage-point volatility increase. Likewise, multiply rho by 0.0001 for an approximate sensitivity to a one-basis-point increase in the domestic USD rate, holding the foreign curve fixed. Theta is annualized, not a one-day cash P&L.

These are local model sensitivities, not guarantees of realized profit or loss. Running from the terminal changes only how the program is launched: the market inputs, Garman-Kohlhagen process, analytic engine, and resulting prices remain the same as in the VS Code workflow.

References

  1. Garman, M. B., & Kohlhagen, S. W. (1983). Foreign currency option values. Journal of International Money and Finance, 2(3), 231–237. https://doi.org/10.1016/S0261-5606(83)80001-1