Sunday, March 13, 2022

Generating Linux programs in Windows Visual Studio C++

You can use Windows 10 and Visual Studio 2022 to generate, debug and analyze Linux binaries:

  1. Install WSL, restart computer
  2. Open cmd, type wsl to enable linux prompt, install tools
    1. sudo apt-get update
    2. sudo apt install g++ gdb make ninja-build rsync zip
  3. Open Visual Studio, on menu Tools - Get Tools and Features, add "Linux development with C++" if you haven't done already:
  4. In Visual Studio, 
    1. Create new project and select CMake project:
    2. After project is created, change Local Machine to WSL:Ubuntu. Change Startup item to your project name:
    3. If Visual Studio notifies you that CMake needs to be updated/installed, let it do it.
    4. Press debug button to build and run:
    5. At the bottom of the screen, in Output window, change it to CMake:
    6. Visual Studio tells you where it has generated the Linux binary. Copy this folder to clipboard:
    7. Go to View - Terminal. In the opened PowerShell terminal at the bottom, type wsl and press enter, the prompt will change to linux :
    8. Type cd and paste the folder you copied:
    9. Now you can also run your Linux binary from terminal:
    10. To use valgrind, first install it in PowerShell by typing sudo apt install valgrind
    11. Now you can use valgrind on your binary without leaving Visual Studio by typing (replace ./CMakeProject4 with your own project name): valgrind --tool=memcheck --leak-check=yes ./CMakeProject4:
    12. To copy the binary to a Windows folder, you can open File Explorer from Linux prompt by typing explorer.exe .:
    13. Congratulations!

No comments:

Post a Comment