Building and Running C++ Code in WSL2 (Linux Debian) with Mingw - Not Always the Last One Running

Abstract: Enables running MinGW C++ executables in WSL2 Debian by configuring interop and preventing path conflicts.

Created: 2026-10-19 by

Building and running C++ executables in WSL2 using MinGW requires explicit configuration because the Windows Subsystem for Linux does not natively execute Windows binaries. You must configure the /etc/wsl.conf file to enable interop, ensure the executable is in the path, and launch it from the Linux shell or via a direct call to wsl.exe.

Understanding WSL2 Interoperability

A common misconception is that WSL2 uses Wine to run Windows applications. This is incorrect. WSL2 utilizes a binary translation layer known as interop. This feature allows Linux processes to directly invoke Windows executables, such as those compiled with MinGW, without an emulator. However, this interoperability is disabled by default in many configurations to prevent accidental execution of Windows binaries within the Linux environment, which can cause confusion regarding file paths and permissions. To build and run C++ code effectively, you must explicitly enable this feature.

Configuring /etc/wsl.conf

The primary step involves editing the /etc/wsl.conf file inside your Debian distribution. This file controls how WSL interacts with the host Windows system. If the file does not exist, you can create it using a text editor like nano or vim. Open the terminal in your WSL2 Debian instance and edit the configuration file:
sudo nano /etc/wsl.conf
Add the following section to the file:
[interop]
enabled=true
appendWindowsPath=false
The enabled=true setting turns on the ability to run Windows executables from the Linux shell. The appendWindowsPath=false option is crucial; it prevents WSL from automatically adding Windows directories to the Linux $PATH. Adding Windows paths to the Linux $PATH often leads to conflicts where Windows commands (like type or dir) shadow legitimate Linux utilities, causing build scripts to fail unpredictably. After saving the file, you must restart the WSL instance for changes to take effect. Run the following command in PowerShell:
wsl --shutdown
Then restart your Debian session.

Installing MinGW in Debian

Once interop is configured, you need a cross-compiler that generates Windows PE (Portable Executable) binaries instead of ELF (Executable and Linkable Format) binaries standard to Linux. In Debian, this package is typically mingw-w64. Update your package lists and install the compiler:
sudo apt update
sudo apt install mingw-w64
This installation provides both 32-bit (i686-w64-mingw32) and 64-bit (x86_64-w64-mingw32) compilers. For most modern applications, you will use the 64-bit variant. Verify the installation by checking the version of the cross-compiler:
x86_64-w64-mingw32-g++ --version
If this command returns a version number, your toolchain is ready. Note that the compiler name differs from the standard Linux g++. Using g++ will compile Linux binaries, while x86_64-w64-mingw32-g++ compiles Windows binaries.

Compiling and Running the Code

Create a simple test file named main.cpp:
#include <iostream>

int main() {
    std::cout << "Hello from WSL2 MinGW!" << std::endl;
    return 0;
}
Compile this file using the MinGW cross-compiler:
x86_64-w64-mingw32-g++ -o main.exe main.cpp
This command produces a main.exe file in your current directory. Because we enabled interop in /etc/wsl.conf, you can now run this executable directly from the Linux shell:
./main.exe
WSL2 will translate this call, locate the Windows subsystem, and execute the binary. The output will appear in your Linux terminal window. Alternatively, you can launch the executable from Windows PowerShell or Command Prompt if you navigate to the shared drive location (usually /mnt/c/Users/YourName/...).

Troubleshooting Missing DLLs

A frequent issue when running MinGW-compiled binaries is missing dynamic link libraries (DLLs). MinGW links against libgcc_s_seh-1.dll and libstdc++-6.dll by default. If these are not present in the same directory as your executable or in the Windows PATH, the program will fail to start with an error about missing modules. To resolve this, you can copy the required DLLs from the MinGW installation directory (typically /usr/x86_64-w64-mingw32/lib/) to your project folder. Or, you can statically link the libraries during compilation by adding the -static-libgcc and -static-libstdc++ flags:
x86_64-w64-mingw32-g++ -o main.exe main.cpp -static-libgcc -static-libstdc++
Static linking increases the size of your executable but ensures it runs on any Windows machine without needing additional library files.

Best Practices for Development

When developing C++ projects that target Windows from WSL2, consider the following best practices to maintain a clean workflow. First, always use absolute paths or properly mapped symlinks when accessing files between the Linux and Windows filesystems. While WSL2 can access Windows files via /mnt/c/, performance is significantly better when working within the native Linux filesystem (/home/). Therefore, keep your source code in /home/ and only move the final executable to a Windows-accessible location if needed for testing outside WSL. Second, be aware that graphical user interface (GUI) applications compiled with MinGW may not display correctly if you are using a headless WSL2 instance or a remote SSH connection. GUI apps require a Windows X server or WSLg. For command-line tools, however, the setup described above is fully sufficient. For more complex setups involving GUI dependencies, see our guide on Building Linux GUI Applications in WSL using GCC/Clang and Running Command Prompt. Finally, remember that debugging MinGW executables requires a Windows-compatible debugger. Standard GDB in WSL2 cannot debug Windows PE binaries directly. You should use Visual Studio Debugger or WinDbg on the Windows side, attaching to the process launched from WSL.

Frequently Asked Questions

Why does my executable say "Permission denied" in WSL?

This usually occurs because the file was created on the Windows side and lacks Unix executable permissions. You can fix this by running chmod +x main.exe in the Linux shell before attempting to run it.

Can I use Clang instead of GCC for MinGW compilation?

Yes, WSL supports clang with MinGW targets. Install the clang package and use x86_64-w64-mingw32-clang++ as the compiler command, following the same linking principles as GCC.

How do I handle large files when compiling?

If you encounter disk space issues during compilation, check your WSL2 virtual hard disk usage. Refer to Failed to Reclaim Disk Space using WSL -- Manage Ubuntu -- set-sparse false for tips on managing storage efficiently.

Does enabling interop slow down WSL2?

Enabling interop has negligible impact on performance for typical development tasks. It only activates when a Windows binary is explicitly called, so it does not affect native Linux operations or compilation times.

What if I get errors about missing headers?

Ensure you have installed the full mingw-w64 package, not just the base compiler. Some headers are located in subdirectories specific to the target architecture. Use apt-cache search mingw to find related development packages if specific libraries are missing.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More