Custom build key binding sublime text - build

I've made a custom build in sublime which runs my program and it works fine. But I have the Makefile build as default. Is there a way, to let Ctrl+B use the default build (in my case Makefile) and have another shortcut (Ctrl+Shift+B) use another build. If yes, how?
I tried using this :
[
{ "keys": ["ctrl+shift+b"], "command": "build buildName" }
]
but it isn't working and watching at the sublime documentation this command is only for the default build selected.
Thanks in advance.

The actual syntax of the keybinding should be like so:
{ "keys": ["f1"], "command": "build", "args": {"build_system": "Packages/Python/Python3.sublime-build"} },
I would actually recommend against using CtrlShiftB as your custom keybinding, as it is already applied to the "Build With" command.

Related

How to compile and run a c++ source file in visual studio code

I've searched for an answer to this question, but couldn't seem to find one. I know that we can use task.json files to automate the build process. But I want to use Visual Studio Code to implement algorithms in C++ for competitive programming. I want to be able to compile a program, and run it all in one go, if there aren't any errors. If there are errors, I would like them to be displayed.
Also, visual studio code comes with an integrated terminal, so it would be nice if the program output could be redirected there.
Also, how can we map a keyboard shortcut to run this task.
I'm using Visual Studio Code 2019 on Windows 10 with the MinGW G++ compiler.
EDIT
I've tried Escape0707's answer below, and I tried executing 'Run Code' with the default key binding of Ctrl + Alt + N but I'm getting this error.
Updated method which combines make and vscode-cpptools debug:
If you don't care about VSCode integrated debugging tools, which will give you the ability to set breakpoints, change variable value during runtime, inspect variable value, and etc, and you want a somewhat easier, simpler, faster, transparent way to invoke the good old command line tools, skip this section and checkout Code Runner below.
The default configurations come with VSCode C++ extension are kind of slow for low-end machines. The worst part is that they will always rebuild your executable, and don't support 'Start Without Debugging'. Below is a workaround for Linux (and of course remote-WSL).
To address the first issue, you setup make (for simple one source file compiling you only need to install make) to build your source codes, and setup the build task in tasks.json. To address the second issue, you create another task just to run the built executable after the first task finished:
Use Intellisense to learn about each properties in configs.
tasks.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"presentation": {
"clear": true,
"focus": true,
"panel": "shared"
},
"tasks": [
{
"label": "make active file",
"type": "shell",
"command": "make",
"args": ["${fileBasenameNoExtension}.out"],
"problemMatcher": "$gcc",
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "run active file executable without debuging",
"type": "shell",
"command": "${fileDirname}/${fileBasenameNoExtension}.out",
"presentation": {
"clear": false
}
},
{
"label": "make and run active file without debuging",
"group": {
"kind": "test",
"isDefault": true
},
"dependsOn": [
"make active file",
"run active file executable without debuging"
],
"dependsOrder": "sequence"
}
]
}
To enable debugging using VSCode in this way, first make sure you added -g compile flag to CXXFLAGS in Makefile.
For quick information about how to write a Makefile, see this, or this, or this. Or check this last part of this answer.
Then, create the following launch.json:
launch.json
{
// 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": "make and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}.out",
"cwd": "${workspaceFolder}",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "${defaultBuildTask}"
}
]
}
Now you can use command palette to try Task: Run Build Task, Task: Run Test Task, Debug: Start Debugging.
Original answer
Please consider Code Runner, as it seems faster (for me) than VSCode's built-in debug procedure for practicing with many small C++ code files. I'll describe how I use that extension to satisfy a similar requirement.
Make sure you've configured your PATH to include clang++ so you can invoke it from the integrated terminal.
You can also use g++ by substitute clang++ below with g++. I prefer clang++ as it provides stricter checks for C++ beginners like me.
Install the extension.
In your VSCode's settings.json, consider adding the following entries:
"code-runner.clearPreviousOutput": true,
"code-runner.preserveFocus": false,
"code-runner.runInTerminal": true,
"code-runner.saveFileBeforeRun": true
And add the last customization code-runner.executorMap to user/workspace setting that describes which command you would like the extension to send to the terminal when current filename's extension meets the specified ones. For example:
"code-runner.executorMap": {
"cpp": "\b\b\b\b\b\b\b\b\b\bclang++ -std=c++17 $fileName -o a.out && ./a.out"
},
The above setting tells the extension, "When see a .cpp file, send 10 Backspace to terminal (to delete any mistyped characters) and call clang++ -std=c++17 *filename* -o a.out && ./a.out.
I use this command on my Linux machine, for Windows, try change the filename extension of the output file to .exe and invoke it with .\a.exe or simply a.exe.
Finally, map the Run Code command to your preferred keybinding in VSCode's Keyboard Shortcuts settings. Mine is to bind it to F5 which is originally bound to Debug: Continue.
Happy coding!
Update about make
Read on to learn how to avoid redundant compiling process and speed up case test by utilizing GNU make. I'll do this on Linux and only for C++, since I have not used make on Windows or OS X and C++ is the best for ACM.
Make sure make is installed and in your PATH
Create a file named Makefile (or makefile) under the same directory you invoke make. (Or in another directory and make -f /path/to/Makefile).
Redefine compiler options to whatever you like in the Makefile, e.g.:
CXX = clang++
CXXFLAGS = -std=c++17 -g -Weverything -Werror
Create auto-target rule for *.out in the Makefile, i.e.:
%.out: %.cpp
$(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $#
Attention: must use Tab to indent the second line, not Spaces.
Change code-runner.executorMap to :
"code-runner.executorMap": {
"cpp": "\b\b\b\b\b\b\b\b\b\bmake $fileNameWithoutExt.out && ./$fileNameWithoutExt.out"
(Optional) To ignore *.out for git:
echo "*.out" >> .gitignore
(Optional) To remove *.out in current directory:
rm *.out
Now the Run Code command will invoke make and make will only regenerate .out file when the corresponding .cpp file is newer than the .out file, thus allows us to skip compilation and proceed with testing even smoother.
The CXXFLAGS is for C++ compiler options, CFLAGS is for C compiler options. You can find other language compiler options and their variable name using make -p, Google and GNU make manual#Automatic-Variables.
To Build/run C++ projects in VS code , you manually need to configure tasks.json file which is in .vscode folder in workspace folder . To open tasks.json , press ctrl + shift + P , and type Configure tasks , and press enter, it will take you to tasks.json
Here i am providing my tasks.json file with some comments to make the file more understandable , It can be used as a reference for configuring tasks.json , i hope it will be useful
After configuring tasks.json , to compile and run your c++ file , press ctrl+shift+B , this is shortcut for running build tools in vscode . Your C++ program will now run on vscode integrated terminal only .
If this presents some issues , then change default terminal to cmd(by default it is powershell in windows) and make sure there aren't any spaces in path to your file .
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "build & run", //It's name of the task , you can have several tasks
"type": "shell", //type can be either 'shell' or 'process' , more details will be given below
"command": "g++",
"args": [
"-g", //gnu debugging flag , only necessary if you want to perform debugging on file
"${file}", //${file} gives full path of the file
"-o",
"${workspaceFolder}\\${fileBasenameNoExtension}", //output file name
"&&", //to join building and running of the file
"${workspaceFolder}\\${fileBasenameNoExtension}"
],
"group": {
"kind": "build", //defines to which group the task belongs
"isDefault": true
},
"presentation": {
"echo": false,
"reveal": "always",
"focus": true,
"panel": "shared",
"clear": false,
"showReuseMessage": false
},
"problemMatcher": "$gcc"
},
]
}
All the properties in the presentation of tasks.json are just used to customize build tasks as per your needs , feel free to change them to what you like best . You can read about presentation properties (and other things) on vscode tasks documentations

Can preLaunchTask and launch start within the same terminal in VSCode?

I am debugging my CPP code with VSCode. I need to use a preLaunchTask to set my environment before my code run. So my code should run after preLaunchTask right in the same terminal. But it start in two different terminal now. How can I do with this?
And btw how can I start the process in the same terminal next time? Some process will start another terminal next time, I am confuse.
My preLaunchTask:
{
"label": "source_setup",
"type": "shell",
"command": "source ./devel/setup.zsh && export ROS_MASTER_URI=http://localhost:11311/ "
},
As stated by #isidorn in this vscode GitHub issue this feature is currently not yet supported. In the meantime, people can achieve the desired behaviour by adding the following code to their .bashrc
# Source ros setup.bash if present
if [ -f '../devel/setup.bash' ]; then . "../devel/setup.bash";fi
If you don't want to manually switch to the terminal once the task has ran, here is a good workaround:
add this line to your launch.json config:
"internalConsoleOptions": "openOnSessionStart"
This will switch to the terminal view once the task script has finished running.
I think you could just use envFile property.
In my case launch for debugging looks like this (this one is used by python, but it also needs sourcing ./devel/setup.bash before running):
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current ROS File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"envFile": "${workspaceFolder}/devel/setup.bash"
}
]
}

Could I use MSBuild as C++ compiler with Visual Studio code if I can't create the vcxproj file?

My ultimate goal is to able to use Visual Studio Code to write and run simple C++ programs. I have installed Visual Studio Code and MSBuild (Visual Studio Build Tools 2017) on my machine.
I do not have Visual Studio IDE installed on my machine. So, I have no easy way to create *.vcproj and *.sln for the code that I write.
So, here is what I do: I write a simple C++ program and save the file as test.cpp. And then, even before creating a build task in VS code, I wanted to verify if MSBuild works. So, I ran the following command.
msbuild.exe /t:ClCompile /p:SelectedFiles="test.cpp"
and it returns the following error:
error MSB1003: Specify a project or solution file. The current working
directory does not contain a project or solution file.
Is it possible to use MSBuild to compile a single C++ file?
Reference: Using MSBuild to compile a single cpp file - This page suggest that I should be able to run MSBuild to compile a single C++ file since VS 2010.
You need to read the page you link to more carefully. MSBuild requires a project file (or a solution file referencing one or more project files) to do anything at all and that in turn is created by the IDE.
I believe that what you are looking for is CL (compiler) and not MSBuild (project tool,...).
I wrote a page with my notes for vscode and c++. There you can also get the task for debugging.
These are the tasks I use for building a single file:
{
"label": "MSVC C++03",
"type": "shell",
"command": "cl.exe",
"args": [
"/EHsc",
"/FC",
"/Od",
"/permissive-",
"/W4",
"/Z7",
"/Fdout/${fileBasenameNoExtension}.pdb",
"/Feout/${fileBasenameNoExtension}.exe",
"/Foout/${fileBasenameNoExtension}.obj",
"${fileBasename}",
],
"group": "build",
"presentation": {
"reveal":"always"
},
"problemMatcher": "$msCompile"
},
{
"label": "MSVC C++17",
"type": "shell",
"command": "cl.exe",
"args": [
"/EHsc",
"/FC",
"/Od",
"/permissive-",
"/std:c++17",
"/W4",
"/Z7",
"/Fdout/${fileBasenameNoExtension}.pdb",
"/Feout/${fileBasenameNoExtension}.exe",
"/Foout/${fileBasenameNoExtension}.obj",
"${fileBasename}"
],
"group": "build",
"presentation": {
"reveal":"always"
},
"problemMatcher": "$msCompile"
}

Can't compile code "launch: program <program_path> does not exist "

I have simple console application in C++ that I succeed to compile with Visual Studio.
I wanted to try Visual Studio Code so I copied the directory to the computer with Visual Studio Code installed.
I installed the C++ extension:
I put break point at the beginning and press F5 and I received an error:
launch: program 'enter program name, for example
c:\Users\student1\Desktop\ConsoleApp\a.exe' does not exist.
Of course the the program does not exist, I am compiling it in order for the code to become the program.
I followed the instruction and I went to the launch.json file:
I changed the "program" value to: "${workspaceRoot}/a.exe" instead of "enter program name, for example ${workspaceRoot}/a.exe".
But the same problem still exist.
Any idea ?
Spent 2 hours on this.
Ideally, VS Code shouldn't make so difficult for beginners
VS Code can give prompts for each installation, etc. automatically, in a step by step manner, like Idea editors, so that it wont be so long procedure for beginners.
Sequence of steps to do (most of the things are one time):
one time:
install a C/C++ complier, add to PATH environment variable
install C/C++ plugin for visual studio code
tell visual studio code where the compiler is and what is the short cut to build and run
these are files under ".vscode" (see below)
every project:
crate a project
build project
run project
Detailed:
One time:
Note: Point 'A' below can be skipped if you already have a compiler.
A. Install a compiler (if you don't have one already)
Example below, installs MinGW c++ compiler on Windows:
Download from here: https://sourceforge.net/p/mingw-w64/mailman/message/36103143/
1. For windows, I downloaded https://sourceforge.net/projects/mingw-w64/files/mingw-w64/mingw-w64-release/mingw-w64-v5.0.3.zip
2. unzip mingw-w64-v5.0.3.zip
3. rename unzipped folder to MinGW, Move it to C:\MinGW\
4. verify that you have "C:\MinGW\bin\gcc.exe" director/file, otherwise make necessary change to folder
B. Add your compiler to PATH environment variable
1. Add "C:\MinGW\bin" to PATH > user environment variable
2. verify gcc command works from cmd
restart your cmd
run below command in 'cmd'
where gcc
The output should be: C:\MinGW\bin\gcc.exe
C. Restart your visual studio code
1. install C/C++ plugin, as below:
From Menu
View > Extension
Search & Install below extension
C/C++
Every project:
Note: You can copy paste the .vscode folder every time
A. Create a below "myproj" folder & files, like below in below structure:
C:\myproj\myfile.cpp
C:\myproj\.vscode\
C:\myproj\.vscode\c_cpp_properties.json
C:\myproj\.vscode\launch.json
C:\myproj\.vscode\settings.json
C:\myproj\.vscode\tasks.json
B. Download & overwrite the above ((5 files)), from below link
https://github.com/manoharreddyporeddy/my-programming-language-notes/tree/master/vscode-c%2B%2B
C. Restart your visual studio/vs code
D. Open project in vs code & run project:
Drag and drop "myproj" folder into visual studio code
BUILD PROJECT: press "Ctrl + Shift + B" to build your myfile.exe
RUN PROJECT: press "Ctrl + F5" to run your myfile.exe
Thats all, hope that helped.
More info: https://code.visualstudio.com/docs/languages/cpp
Optional
To format C++ better
C++ formatting
1. Install Clang:
Download from: http://releases.llvm.org/download.html#5.0.2
I have downloaded for windows
"Pre-Built Binaries:" > Clang for Windows (64-bit) (LLVM-6.0.0-win64.exe)
2. Select Add to PATH while installing.
3. Install vs code plugin "Clang-Format" by xaver, this wraps above exe.
4. Restart visual studio code.
Note:
Issue: As of June 2018, Clang does not format the newer C++17 syntax correctly.
Solution: If so, move that code to another file/ comment & restart the vs code.
That's all. Now press Alt+Shift+F to format (similar key combination in other OS)
The error ".exe file does not exist" in vscode can occur because of the following reasons:
If the file name contains white spaces
If there is re-declaration of variables or other kind of compilation errors
This problem is mainly due file name , as per below table the name of the binary will be audioMatrixBin in windows folder not audioMatrixBin.exe, but we have to mention filename.exe here.
{
"name": "(Windows) Launch",
"type": "cppvsdbg",
"request": "launch",
"program": "audioMatrixBin.exe",
"args": ["AudioMxrMgr4Subaru.conf"],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true
}
]
}
Go to launch.json(we've encounter problem with .json file that's why we're here)
Change 'cwd' & 'miDebuggerPath' where your 'gdb' is(mine is default).
"cwd": "C:\\MinGw\\bin",
"miDebuggerPath": "C:\\MinGw\\bin\\gdb.exe"
(you can copy-paste if yours is default too).
Now run with 'gcc.exe-Build and debug active file'
(run your file with this option, this should run)
Make sure your "program" and "cwd" properties are actually correct. Check the path it tells you and compare with the path you want them to be.
BUILD your PROJECT .exe file : press "Ctrl + Shift + B" to build your example.exe
It seems that launch.json file needs to have the correct configs.
please check the configurations as per the below link, if you are using VS build tools
https://code.visualstudio.com/docs/cpp/config-msvc
or delete the launch.json file, gotoRun > Add Configuration... and then choose C++ (Windows), Choose cl.exe build and debug active file. Check the new name in launch.json and try again.
This video explain it very well how to setup vscode for c, I did it on Ubuntu.
https://www.youtube.com/watch?v=9pjBseGfEPU
Then I use this reference to setup c++,
https://code.visualstudio.com/docs/cpp/config-linux
I just had to replace "command": "/usr/bin/gcc" with
"command": "/usr/bin/g++",
from the example on the video.
and you can update the label on both tasks and launch if you want it.
this is how my c++ setup ended up.
tasks.json for c++
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
// "command": for classic c, "command": "/usr/bin/gcc",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/bin/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"isDefault": true,
"kind": "build"
}
}
]
}
launch.json for c++{
// 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": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/bin/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: g++ build active file"
}
]
}
In your launch.json file check the "miDebuggerPath" and see if the same path is defined in your environment variables.
To resolve this proble one has to make sure three things are in order:
You have successfully downloaded and install the gcc (compiler) and gdb (debugger). To check this you should be able to type
gcc --version
and
gdb --version
and get the correct results
Once done with this step compile the myfile.c using this command.Make sure that your file has a main() function ,otherwise the produced myfile.exe will not be recognised by the debugger.
gcc -c myfile.c -o myfile.exe
Add a launch configuration using gcc.
In the launch configuration
manually add the path to the executable "program": "${workspaceFolder}/myfile.exe"
In the launch configuration
manually add the path to the debugger "miDebuggerPath": "C:/MinGW/bin/gdb.exe"
Nuke everything and use the build active file tasks:
Delete all files within the .vscode folder.
Select Terminal > Configure Tasks
Select appropriate system task (i.e. for Mac, C/C++: clang build active file).
Open .vscode/tasks.json
Configure C++ language standard by specifying the std flag (i.e. "-std=c++17") at the top of the args array.
the problem for me was an error during the run time that the compiler didn't notice before. then the .exe file didn't built, therefore the .exe file does not exist so you have to check if your script is fine even if no error is found by the debugger.
{In launch.json file where name : (Gdb) launch ,
step 1: enter the complete address of program for eg, c:/users/.....xyz.exe.
step 2: In Mi-debugger path complete address of bin in mingw folder which contains the Gdb debugger so the address would be c:/mingw/....gdb.exe repeat step 2 for the first configuration in launch.JSON
step 3 IN CWD , copy the same path but only till /bin
That should work }

Sublime Text 2 how to cancel automatic build?

I'm having problem trying to stop Sublime Text 2 from build on save. I had previously installed SaveAllOnBuild plugin but I removed it. I have also made sure that Tools -> Save All on Build is turned off. In addition, I also checked my keyboard mapping, and Cmd+S is not listed as the keyboard binding
This is the snippet from the default binding file. User binding file is empty
{ "keys": ["f7"], "command": "build" },
{ "keys": ["super+b"], "command": "build" },
{ "keys": ["super+shift+b"], "command": "build", "args": {"variant": "Run"} },
I don't understand why Sublime keeps build on save. Any information would be nice. Thanks.