Building and Running C++ Code on WSL2 (Linux Debian) with MinGW - Not Always the Last One Running
Cross-platform development is an essential skill for modern software developers. In this article, we will explore how to build and run C++ code on Windows Subsystem for Linux version 2 (WSL2) using Linux Debian and MinGW. We will also discuss some common pitfalls and solutions when working with this setup.
Prerequisites
Before we begin, ensure you have the following installed:
- Windows 10 with WSL2 enabled
- Linux Debian installed on WSL2
- MinGW installed on Windows
Building C++ Code on WSL2
To build C++ code on WSL2, open a Linux terminal and navigate to the directory containing your source code. You can then use the following command to compile your code:
g++ -o output_file source_file.cppReplace output_file with the desired name of the compiled binary and source_file.cpp with the name of your C++ source file. For example:
g++ -o my_program main.cppRunning the Compiled Binary on Windows
After building the binary on WSL2, you can run it on Windows using MinGW. To do this, open a MinGW terminal and navigate to the directory containing the compiled binary. You can then run the binary using the following command:
.\\output_file.exeReplace output_file.exe with the name of the compiled binary. For example:
.\\my_program.exeCommon Pitfalls and Solutions
When working with this setup, you may encounter some common pitfalls. Here are some solutions to these problems:
-
Error:
bash: ./output_file: Permission deniedThis error occurs when you try to run the compiled binary on WSL2 without giving it execute permissions. To fix this, run the following command on WSL2:
chmod +x output_file -
Error:
wsl: /mnt/c/path/to/binary: Permission deniedThis error occurs when you try to run the compiled binary on WSL2 from a Windows path. To fix this, copy the binary to a Linux path and run it from there. For example:
cp /mnt/c/path/to/binary ~/binary./binary -
Error:
The code execution cannot proceed because VCRUNTIME140.dll was not foundThis error occurs when the compiled binary depends on a dynamic link library (DLL) that is not present on Windows. To fix this, install the Visual C++ Redistributable for Visual Studio 2015, 2017, or 2019, depending on the version of MinGW you are using. You can download it from the following link:
https://support.microsoft.com/en-us/topic/the-latest-supported-visual-c-downloads-2647da03-1eea-4433-9aff-95f26a218cc0
In this article, we have discussed how to build and run C++ code on WSL2 using Linux Debian and MinGW. We have also covered some common pitfalls and solutions when working with this setup. By following the steps outlined in this article, you can take advantage of the power of Linux and the convenience of Windows for your C++ development needs.