How to pass comma-separated options to the g++ linker with VSCode? - c++

I need to pass the arg -Wl,-Bstatic,--whole-archive to g++.
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "shell: g++.exe build active file",
"command": "C:\\MinGW\\x86\\bin\\g++.exe",
"args": [
"-g",
"${file}",
"-Wl,-Bstatic,--whole-archive",
"-Xlinker",
"-Map=${fileDirname}\\${fileBasenameNoExtension}.map",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "C:\\MinGW\\x86\\bin"
},
"problemMatcher": [
"$gcc"
],
"group": "build"
}
]
}
It gives me in output this in the terminal.
Executing task: C:\MinGW\x86\bin\g++.exe -g 'c:\Users\remi\Desktop\OK - VSCode\loaderstack.cpp' -Wl,-Bstatic,--whole-archive -Xlinker '-Map=c:\Users\remi\Desktop\OK - VSCode\loaderstack.map' -o 'c:\Users\remi\Desktop\OK - VSCode\loaderstack.exe' <
At line:1 char:84
+ ... e -g 'c:\Users\remi\Desktop\OK - VSCode\loaderstack.cpp' -Wl,-Bstatic ...
+ ~
Missing argument in parameter list.
At line:1 char:93
+ ... Users\remi\Desktop\OK - VSCode\loaderstack.cpp' -Wl,-Bstatic,--whole- ...
+ ~
Missing argument in parameter list.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingArgument
Is there anyway to build inside VSCode with these comma-separated args ?

I originally answered this question (like a dumb dumb) as if you were using Linux, so I deleted that answer and included a new one for PowerShell.
This is sort of a common problem when dev's use GCC with Powershell. The problem is that PowerShell is very programmatic in the way it implements its interface, and the way that it executes commands. With Linux, CLI's are all written opensource (mostly) and are developed by the developers, where powershell is created by a company that dictates how every little detail works (there are benefits, and downsides to both). PowerShell has aspects/features (or w/e you want to call them) that just feel like somthing a programming language has, for example PowerShell has scopes, and what you pass to powershell gets parsed according to the context (or scope) that your currently in. The problem you are dealing with is that your command, that your handing GCC through your VS Code v2 Task is not being parsed properly due to the context in which the task is handing it to Power-shell.
YOU HAVE 2 OPTIONS
Option #1
The first option is to use a scope where the parser will correctly interoperate the command.
Remember, your using a VSCode task, powershell & gcc, to make sure communication succeeds across all three, you need to include the scope to use in what you are communicating. To do that we want to make use of the...
Call Operator &
To use the call operator just format the initial command to execute as shown in the code block bellow:
"command": "& C:\\MinGW\\x86\\bin\\g++.exe",
Where I know that this is a valid solution to your problem, I am currently on a Linux System, I have windows dual booted, but I am too lazy to switch over to it, so just in-case something needs to be tweaked, use the link for the Call Operator I posted above, MS documentation is very good, and very specific about how to implement its software-technologies
Option #2
Your second option takes a totally different route than the first.
Instead of dealing with the scope being the problem, your gonna deal with Power-shell's inability to parse the MingW GCC Command.
To deal with Power-shell's parsing issue, we will tell it to stop parsing the command, henceforth, the...
stop-parsing flag --%
(For the semantics police-type of developers: I think its technically a token, not a flag)
Using the flag looks like this: gcc %--
So the whole command should look somthing like this:
"args": [
"--%"
"-g",
"${file}",
"-Wl,-Bstatic,--whole-archive",
"-Xlinker",
"-Map=${fileDirname}\\${fileBasenameNoExtension}.map",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
Again, I included the link to the docs for the stop-parsing token above, just in-case something needs to be tweaked.
The example I showed above is somthing I had to use on a project that I worked on for a very long time, because of that experiance, I perfer to use the no
Somthing else that I don't know much about, by I read about when I DDG'd the links to Microsoft-site that might, maybe work is using the Arguments mode, which seems to be similar to the stop parsing command?
Anyhow, here is the link if you want to read about it.

I should say that I have not tried this approach, but I think it will work.
I suggest that you escape , in powershell using `. Try it in your config file like this:
"-Wl`,-Bstatic`,--whole-archive",
I'm not sure if it works, but since it worked for echo hell`,o`,o, I guess everything will be fine. Please let me know if this approach works.

Related

How to display the full error messages in VScode?

I've got a problem that's bothering me for a long time. I use VScode on macOS with standart clang compiller. Almost all error messages produced by the "gcc" are cut, and don't help me at all. I do not know is it a VScode thing or my compilling settings are wrong. Also, if someone could say why just using "usr/bin/clang++" in command parameter is not working, it'll be excellent...
Settings
Problem
The problem matcher of the task shows only the first line of error messages. GCC and Clang wrap error messages on multiple lines resulting truncated errors in the VSCode "Problems" panel and tooltips.
Pass the option -fmessage-length=0 to the compiler to direct it to not wrap lines. Modify "args" in your config.
"args": [
"-fmessage-length=0",
"-Wall",
"-Wextra",
"-std=c++17",
"-g",
"${fileDirname}/**.cpp",
"-o",
"${fileDirname}"/${fileBasenameNoExtension}"
],
I'm not sure what it means that error messages "are cut", does that mean they are deleted? It looks like from your picture that they are still showing. If you are getting error messages that you fixed, sometimes another build is required for phantom errors to go away.
Addressing the second part, if you moved the bin directory from XcodeDefault.XcodeToolChain/ straight to the usr/ directory, then you could set the command to
"command": "usr/bin/clang++"
I doubt that clang installed directly to your user folder, however, and it is probably not good practice to move it there since other programs and tasks may still depend on the old location.

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'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 }

Running (lein) REPL in VS CODE

Is there a way to use lein's REPL in VS Code? I mean, using tasks.js, or something.
I wanted an integrated enviroment to run, test and build my clojures applications. I think maybe I could achieve something like this using vs code, because it has support to third parties compilers.
I could use lein run, but it did not work with lein repl.
I've read tasks' documentation, but there's nothing related to REPL.
Here's the tasks.js code I've used:
{
// See http://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "lein",
"tasks":
[
{
"taskName": "run",
"showOutput": "always",
"args": ["run"],
"isBuildCommand": true,
"isWatching": false
},
{
"taskName": "repl",
"showOutput": "always",
"args": ["repl"],
"isWatching": true
}
],
"isShellCommand": true
}
As the author of Calva I can recommend it. 😀
Seriously, at the moment it is supporting interactive programming the best. There is a short summary of what it can do in the Editors section of the shadow-cljs user guide: https://shadow-cljs.github.io/docs/UsersGuide.html#_calva_vs_code
Updated (July 2021)
For Clojure and ClojureScript development in VSCode, Calva is the recommended plugin, as it has added a lot of support.
Original Answer (2016)
There's extension available now which you can use.
Github
VS Code Market Place
I don't believe a real REPL is possible at the moment in VSCode.
With that being said, this is currently being worked on over here: https://github.com/Microsoft/vscode/issues/547

Custom build key binding sublime text

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.