c++visual-studio-codevscode-code-runner

Cpp in VSCode with Code Runner - How to compile to other folder


I'm using VS Code to program in C++. When I run the code (using the "Code Runner" extension), the .exe file stored in the same folder. I've seen in many projects that they stored it in a /bin folder. Is it possible to automatically store it in there? (Also create the /bin folder if it doesn't exists).


Solution

  • I figured out 2 ways how to do your task:

    1. In this scenario you have to create bin folder manually

      So let's configure your VScode extension

      From extension page follow this step to open settings

      From extension page follow this step to open settings enter image description here

      In settings tab open "Edit in settings.json"

      enter image description here

      In your Json find "code-runner.executorMap"::cpp and insert the following command instead of the existing one

      cd $dir/bin && g++ ../$fileName -o $fileNameWithoutExt && $fileNameWithoutExt
      

      So it would look like this enter image description here

      P. S. This command works on Windows, and may not work on linux. I guess If the previous command does not work in linux, then try the next one

      cd $dir/bin && g++ ../$fileName -o $fileNameWithoutExt && ./$fileNameWithoutExt
      

      And I think, if you're linux user you can automate everything with a command(but unfortunately I can't test it)

      cd $dir && mkdir -p bin && cd bin && g++ ../$fileName -o $fileNameWithoutExt && ./$fileNameWithoutExt
      
    2. In this scenario you have to switch execution to integrated terminal(so output will change a little bit) by adding to your json following line

      "code-runner.runInTerminal": true
      

      and changing your cpp command to:

      for windows

      cd $dir && mkdir -Force bin > $null && cd bin && g++ ../$fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt
      

      and I guess for linux

      cd $dir && mkdir -p bin && cd bin && g++ ../$fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt
      

      So it would looks like this enter image description here