How to run C++ on MS Visual Studio Code

I became too lazy because I want to run all programs in one tool in one platform. Then this visual studio code came as a rescue!! Now, I want to learn how to run the C++ on VS code with command line arguments. But, this post will cover how to run the C++ on VS code from "extensions required" to "running C++ with command arguments".




I've installed the following extensions in the MS VC already.

  1. C/C++ 
  2. C/C++ Extension Pack
  3. Better C++ Syntax
  4. C/C++ Themes


1. Install Homebrew

1. If homebrew is not installed in your machine, copy and paste this command in your terminal.

M1 Mac

arch -x86_64 ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install)" < /dev/null 2> /dev/null

2. If homebrew is installed, you will get the output while executing "brew help". If not, "no command found"

Shirleys-MacBook-Air:~ shirley$ brew help
Example usage:
  brew search TEXT|/REGEX/
  brew info [FORMULA|CASK...]
  brew install FORMULA|CASK...
  brew update
  brew upgrade [FORMULA|CASK...]
  brew uninstall FORMULA|CASK...
  brew list [FORMULA|CASK...]

Troubleshooting:
  brew config
  brew doctor
  brew install --verbose --debug FORMULA|CASK

Contributing:
  brew create URL [--no-fetch]
  brew edit [FORMULA|CASK...]

Further help:
  brew commands
  brew help [COMMAND]
  man brew
  https://docs.brew.sh
Shirleys-MacBook-Air:~ shirley$ 

2. Install MinGW

Intel Mac

brew install MinGW-w64

M1 Mac

arch -x86_64 brew install MinGW-w64

The above command didn't work, and it threw the below error.

Shirleys-MacBook-Air:~ shirley$ arch -x86_64 brew install MinGW-w64
Running `brew update --auto-update`...
==> Homebrew is run entirely by unpaid volunteers. Please consider donating:
  https://github.com/Homebrew/brew#donations
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> New Formulae
astro                                                     flock

Error: Cannot install under Rosetta 2 in ARM default prefix (/opt/homebrew)!
To rerun under ARM use:
    arch -arm64 brew install ...
To install under x86_64, install Homebrew into /usr/local.
Shirleys-MacBook-Air:~ shirley$


arch -arm64 brew install MinGW-w64


Shirleys-MacBook-Air:~ shirley$ arch -arm64 brew install MinGW-w64
==> Downloading https://ghcr.io/v2/homebrew/core/gmp/manifests/6.2.1_1
######################################################################## 100.0%
==> Downloading https://ghcr.io/v2/homebrew/core/gmp/blobs/sha256:491220f1ff2c662b96295d931a80702523eeaee681d7305f
==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:491220f1ff2c662b96295d931a807
######################################################################## 100.0%
==> Downloading https://ghcr.io/v2/homebrew/core/isl/manifests/0.24
######################################################################## 100.0%
==> Downloading https://ghcr.io/v2/homebrew/core/isl/blobs/sha256:cf7f8b77fc0e51bc9c9921306737176e6f9e03062255a525
==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:cf7f8b77fc0e51bc9c99213067371
######################################################################## 100.0%
==> Downloading https://ghcr.io/v2/homebrew/core/mpfr/manifests/4.1.0
######################################################################## 100.0%
==> Downloading https://ghcr.io/v2/homebrew/core/mpfr/blobs/sha256:9df11560dd3650ffae35c134cef6e0e91aad0e862f5c889
==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:9df11560dd3650ffae35c134cef6e
######################################################################## 100.0%
==> Downloading https://ghcr.io/v2/homebrew/core/libmpc/manifests/1.2.1
######################################################################## 100.0%
==> Downloading https://ghcr.io/v2/homebrew/core/libmpc/blobs/sha256:6a93bd78c1b55f8b29e11fd1e9c68c6c305ffe74aa5b9
==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:6a93bd78c1b55f8b29e11fd1e9c68
######################################################################## 100.0%
==> Downloading https://ghcr.io/v2/homebrew/core/mingw-w64/manifests/10.0.0_1-1
######################################################################## 100.0%
==> Downloading https://ghcr.io/v2/homebrew/core/mingw-w64/blobs/sha256:857aecb324bf425ca3ef2bcfd462a4909df2f6d515
==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:857aecb324bf425ca3ef2bcfd462a
######################################################################## 100.0%
==> Installing dependencies for mingw-w64: gmp, isl, mpfr and libmpc
==> Installing mingw-w64 dependency: gmp
==> Pouring gmp--6.2.1_1.arm64_big_sur.bottle.tar.gz
  /opt/homebrew/Cellar/gmp/6.2.1_1: 21 files, 3.3MB
==> Installing mingw-w64 dependency: isl
==> Pouring isl--0.24.arm64_big_sur.bottle.tar.gz
  /opt/homebrew/Cellar/isl/0.24: 73 files, 7.3MB
==> Installing mingw-w64 dependency: mpfr
==> Pouring mpfr--4.1.0.arm64_big_sur.bottle.tar.gz
  /opt/homebrew/Cellar/mpfr/4.1.0: 30 files, 5.2MB
==> Installing mingw-w64 dependency: libmpc
==> Pouring libmpc--1.2.1.arm64_big_sur.bottle.tar.gz
  /opt/homebrew/Cellar/libmpc/1.2.1: 13 files, 433.1KB
==> Installing mingw-w64
==> Pouring mingw-w64--10.0.0_1.arm64_big_sur.bottle.1.tar.gz
   /opt/homebrew/Cellar/mingw-w64/10.0.0_1: 7,692 files, 911.6MB
==> Running `brew cleanup mingw-w64`...
Disable this behaviour by setting HOMEBREW_NO_INSTALL_CLEANUP.
Hide these hints with HOMEBREW_NO_ENV_HINTS (see `man brew`).
Shirleys-MacBook-Air:~ shirley$ pwd
/Users/shirley
Shirleys-MacBook-Air:~ shirley$

3. Install Code runner in Visual Studio Code 




From the code runner, I've got the following:
  • To run code:
    • use shortcut Ctrl+Alt(Option)+N
    • or press F1 and then select/type Run Code,
    • or right click the Text Editor and then click Run Code in editor context menu
    • or click Run Code button in editor title menu
    • or click Run Code button in context menu of file explorer
  • To stop the running code:
    • use shortcut Ctrl+Alt(Option)+M
    • or press F1 and then select/type Stop Code Run
    • or click Stop Code Run button in editor title menu
    • or right click the Output Channel and then click Stop Code Run in context menu

4.  Run the C++ Program 

Right click on the text editor and then click "Run code"



I've got the output in the output window. Hurray!! Also, there is another file in the name "helloworld" is shown. This is .exe file. If you delete this and rerun the code, it will be generated again. 



If you don't save the file, you will get the below error.

Undefined symbols for architecture arm64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

This error might also occur if the function is defined first and later the class member function declaration is found.

5. Get the input from the user


In the output window, I wasn't able to enter the username. To fix this, go to Code->Preferences->Settings, search 'Run in Terminal', and tick the check box.



To stop the running code, press ctrl+option+M. 


6. Run the program with Command Line Arguments

The below one is usual because ultimately we pass only one argument via command line. 



To clear the terminal rubbish, press "Command+Shift+P". This will open a command pallette, and now type "Terminal: Clear"


We need a different setup to pass the command arguments. 

What is command line arguments? 

The arguments which are the basically passed while executing the program, are actual arguments to the main() function. 



How can we achieve the similar in the VS code?

i) On the Run & Debug pane, click on the "crate a launch.json file"
If you are not able to find launch.json, first run the program, launch.json will open automatically.



ii) Click on the "Add Configuration"



iii) Select the "C/C++ (lldb) launch"





iv) Modify the launch.json

Modify the launch.json as below. Just change the program and args. 

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [

        {
            "name": "(lldb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/cmdlineargs",
            "args": ["hello", "world"],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "lldb"
        }

    ]
}


v) Run & Debug 

Click on the 'Run & debug pane', and click on the play button. You will get the output in the 'Debug console' but not in the output


7) File name as Command Line Arguments

Instead of the actual arguments, we can give the filename enclosed ".


I haven't demonstrated the actual program here, but it could read the file content and return the proper output.

A Few Errors & Solution 

Shirleys-MacBook-Air:sampleProg shirley$ cd "/Users/shirley/Documents/CPProgramming/sampleProg/" && g++ main.cpp -o main && "/Users/shirley/Documents/CPProgramming/sampleProg/"main
main.cpp:11:8: error: unknown type name 'constexpr'
static constexpr int totalOrders = 5;

Go to Settings > User Settings In here, search for Run Code Configuration:

Under this menu, find: "code-runner.executorMap"

Edit this Setting by adding it to User Setting as below for C++17 support:

"code-runner.executorMap":{
    "cpp": "cd $dir && g++ -std=c++17 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
},




Reference:

UTube Link

Debugging and Command Line Arguments



Comments