Related
I am new to Visual Studio Code and I am just starting to learn the basics of using it to compile my C++ projects. I have ran into an issue where when having a folder 'opened' in Vs code, and then having an inner folder with my 'main.cpp' file inside of it, when compiled creates the 'main.exe' outside of the innerfolder, I don't want this to happen and want the executable which belongs to that main.cpp, inside of the inner folder so that both are stored in the same folder, to me that makes more sense than it being outside of the intended folder. I really don't know where to look to change this behaviour.
Here is an example of what I mean:
Update: Will post an answer to my own problem soon
Update2: I answered it in full detail for anyone ever having this problem/question
I came up with an easy solution. You only have to hide the files with extension .exe. With your answer many people get confused so you have to follow some steps.
step 1: go to files
step 2 : click on preferences-->then settings
step 3 : then search for "exclude file"
step 4 : select add pattern
step 5 : "**/*.exe" add this -->then click ok
step 6 : close the visual studio code then open it again
The process is very simple.
The following process shows how to create/make executable/.exe file in your provided/specific folder
goto Command Palette... by pressing Ctrl + Shift + P
press Backspace to remove > symbol
search tasks.json file, and hit Enter
-. in tasks.json file, you have to look for the following code (Note: this code can be shown 2 or 3 times in the file. Perform the operation for everyone)
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
replace the code "${fileDirname}\${fileBasenameNoExtension}.exe" with your new path, for example, i have a new folder named as "myNewFolder" in my workspace foler, i will replace it as
"${fileDirname}\myNewFolder\${fileBasenameNoExtension}.exe"
hit Ctrl + s to save changes
Now, the following process shows how to run/launch your executable/.exe file provide in your allocated folder/location
goto Command Palette... by pressing Ctrl + Shift + P
press Backspace to remove > symbol
search launch.json file, and hit Enter
look for the key named as "program"
-. it will be as follows
"program": "${fileDirname}\${fileBasenameNoExtension}.exe",
change the filepath. in my case, i will change it as follows
"program": "${fileDirname}\myNewFolder\$fileBasenameNoExtension}.exe",
Save changes
If you're using Code Runner extension, then :
Press Ctrl + Shift + P
step1
delete the ">" symbol (press Backspace to delete)
search "settings.json" which in AppData directory
step3
then you can look at "code-runner.executorMap", in "cpp" line. You can type that arguments
"code-runner.executorMap": {
"javascript": "node",
"java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
"c": "cd $dir && gcc $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
"cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt", // <-- This
"objective-c": "cd $dir && gcc -framework Cocoa $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
"php": "php",
"python": "python -u",
//etc.
},
"code-runner.runInTerminal": true,
Note :
Actually the argument in step 4 is default settings. So, you don't have to edit it if it's your first time using it.
but if u want to customize the argument (in most cases is used to change the output directory), that is the place you'll be used for.
e.g. in my case, I want to separate the .cpp and .exe files to "src" and "bin" folder, so :
"cpp": "cd $dir && g++ $fileName -o ..\\bin\\$fileNameWithoutExt && ..\\bin\\$fileNameWithoutExt",
result :
The separate folder look like : folder_screenshot
Terminal :
PS C:\Coding\C++\src> cd "c:\Coding\C++\src\" ; if ($?) { g++ string.cpp -o ..\bin\string } ; if ($?) { ..\bin\string }
Hi
Hope it works
PLEASE READ IT IS A FULL AND VERY DETAILED EXPLANATON ON A POTENTIAL BUG, WHICH COULD AFFECT WORKFLOW, VISUAL STUDIO HAS YET TO FIX THIS! I WILL REPORT THIS AS SOON AS POSSIBLE
So I've been ripping my hairs out my head with this non-sense of a problem, but finally I have come to a conclusion that Visual Studio has a very hidden bug (since I was not able to find anyone with a similar question/problem), or very unclear documentation.
The initial problem was that if I were to have (I will give a clearer example below) an outer folder opened in Visual Studio Code with an inner folder inside which had the main.cpp file, Visual Studio Code would not budge and would put the main.exe file in the outer folder and not the inner one, you can imagine why this would become a problem if I had many other inner folders inside the outer one and all had their exe file called main.exe.
Let me give you an example of what I mean:
Suppose I have the following path (with main.cpp already having code inside) - outer-folder\inner-folder\main.cpp
Now I open the outer-folder in Visual Studio Code. The following is what it should look like if opened in Visual Studio Code for the first time, without having built or compiled anything
After opening outer-folder for the first time in Visual Studio Code
If I were to try and Ctrl + F5 this now, using the option given by Visual Studio Code of... C++ (GDB/LLDB) ---> g++.exe - build and debug active file, the following would be seen on screen:
After Ctrl + F5 and following options as stated in my explanation
In this case I am in my D: drive and in the example path stated at the beginning of my explanation. The error is saying that main.exe doesn't exist in the inner-folder, which is completely true, it exists inside the outer-folder. Why? Because we need to edit the tasks.json (already misleading information by Visual Studio Code, by inclining me to open the launch.json file, although they are correct to some extent since it is saying launch.json can't find the file to launch so maybe you got your path wrong in there, it would be helpful to also have another option for the tasks.json) which is located in the folder automatically made by Visual Studio Code .vscode along with launch.json.
When in the tasks.json file, there is a variable (if you may call that, though I think there is a different name for that), called args...inside that ([]) are the arguments that Visual Studio Code automatically passes in to the terminal to compile and build your C++ code. The details of all the arguments passed in aren't important for this problem, but the second one (${file}) is referring to the file which we are trying to run, as stated in https://code.visualstudio.com/docs/editor/variables-reference (keep this open as we will need it), the next one (-o) is just telling it to output it like and where the forth argument specifies. The forth one is the really important one here, if we go back to the link which has a reference of the variables that Visual Studio Code provides, ${fileDirname} "should" infact mean the same as saying outer-folder\inner-folder...right? NO! It is wrong, it is actually saying outer-folder, which is the reason why main.exe is being built outside of inner-folder, so we already have a red flag of some type of misinformation from the docs or some type of bug.
Now as the docs that Visual Studio Code provide about gcc on VSC (https://code.visualstudio.com/docs/cpp/config-mingw) we can change somethings, so that the program is built and output in a different location, to do so we need to go into the tasks.json and from there changing the forth argument in args to ${fileDirname}\\inner-folder\\${fileBasenameNoExtension}.exe, now don't reach for the Ctrl + F5 key yet, I need to explain why that won't work, but first let's try something out...press Ctrl + Shift + B, that will build your program but not run it (if you are following this make sure to be building the correct file and not trying to build tasks.json itself lol), now when we do that we can see that another main.exe file will have been built and output in the correct location output is in the correct location. Ok now the docs on configuring mingw in Visual Studio Code suggest than now you can run your file by going to the terminal and running it from there (no need for an explanation on how to do that). What is the fun in that though what if you want to debug it? Here is where we are going to find another potential bug or very bad documentation surrounding this. If we open our launch.json now (this is the file that is ran when you press Ctrl + F5) and then we look at the variable (again I'm nearly 100% sure that is not what it is called but I don't know what to call it at this point) program: here is where you tell launch.json where the location to the file you want to run is, in our case it is where our main.exe should be located. Since we have fixed the issue with in the tasks.json and can now build with Ctrl + Shift + B every time we want to rebuild in the right location, we can now run with Ctrl + F5, right? NOPE! This is where the next bug/bad documentation comes along! If you look at the very bottom of the file there is a "preLaunchTask:" this is the name of the value stored in "label": back in our tasks.json, and it has to match perfectly so that launch.json knows which task to run when invoked. The problem is that even though they match automatically already (as their names are the same by default), it still doesn't work, Visual Studio Code for some reason say, YOU KNOW WHAT SACK YOUR TASKS.JSON WE WILL OVERWRITE THAT AND USE THE DEFAULT ONE! Even if your the default name matches the default on launch.json, it doesn't run your tasks.json it overwrites it with the default one (not 100% sure what it does but that is my best guess, as it 100% doesn't run our one), now the interesting bit is that when we change both the "preLaunchTask": and the "label": to the same thing just anything else than the default one (even add one more character anywhere but make sure both match), when we do Ctrl + F5 it now runs our tasks.json! Yet... all of this for nothing because at the end of the day we had to hard code that tasks.json and we would have to do that for every file that we want stored in some other inner folder! You can fix this (as I later found out) by just opening that folder (inner-folder) as the main one instead of the outer-folder, and boom problems fixed, but then you can't see your whole project as you would have been able to, had your outer-folder been opened.
ive been trying to run c++ codes on sublime for a while but im having this problem "The system cannot find the file specified."
i tried googling for solutions but couldnt find any answer:
As you only specify input.txt without full path it's looking for it in the current folder the program is run: C:\Users\AboodPC\Desktop\Programs.
So either make sure C:\Users\AboodPC\Desktop\Programs\input.txt exists, or specify the full path in shell_cmd after the >.
Just create an input.txt file to take input into the program at run time.
In sublime text 3
Simply name your input file as "inputf.in"
And output file as "outputf.in"
And create new build system
Tool-->bulid system -->new build system
And paste below code
{"cmd": ["g++.exe","-std=c++14", "${file}", "-o", "${file_base_name}.exe", "&&" , "${file_base_name}.exe<inputf.in>outputf.in"],"selector":"source.cpp","shell":true,"working_dir":"$file_path"}
And save as name as"c++14.sublime-build"
And run the program ctrl+shift+B
I'm a complete novice to VS code, and I've only been coding with C++ for around a month. I tried this bare bones program to make sure things were set up correctly:
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout << "Hello world" << endl;
vector<int> v;
return 0;
}
Nothing shows up when running the executable. Removing the vector declaration causes the program to run normally.
I did find this which encountered a similar problem with declaring a string, and the solution (static linking with -static-libstdc++) works for me, though the author who gave the solution wasn't entirely sure why it worked either.
However, since I'm a noob, I don't understand that well why static linking fixed my problem, even after reading this, and am worried about some of the drawbacks mentioned (it recommends only linking statically if you absolutely have to since disadvantages outweight advantages), so I was wondering if there was some other solution besides static linking.
EDIT: Clarification--the program's outputs now show up normally in terminal, but in the output window, the same exit code still appears.
Configure VSCode as given below for "VS Code C++ : exited with code=3221225785"
Install the Code Runner Extension of Visual Studio Code.
Open the Settings(Seetings.json).
Search "code-runner.executorMap" in the Search bar.
modify
"cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
to
"cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt -static && $dir$fileNameWithoutExt",
After that Right Click on source code file select the option Run Code.
For DEBUG:
add an extra parameter "-static" in "args" of tasks.json file.
Before:
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
After:
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe",
"-static"
],
"- static" is static linking parameter when we compiling and running.
I also encountered the same situation, due to the environment variable access error, because I installed MATLAB on my computer first,the environment variable D: matlab\bin also contains the libstdc++-6.dll link library, so the computer will first access D:\ matlab\bin instead of C: \mingw64\bin. So what we need to do is to move the C:\ mingw64\bin environment variable in front of the D:\ matlab\bin environment variable in the computer properties environment variable to solve this problem。
For me solved when I put the file libstdc++-6.dll on folder that I needed debug.
This file is in "\MinGW\bin".
I am using Visual Studio Code in my C++ project. I installed Microsoft C/C++ Extension for VS Code. I got the following error:
#include errors detected. Please update your includePath. IntelliSense features for this translation unit (/path/to/project/file.cpp) will be provided by the Tag Parser.
Close and re-open Visual Studio Code.
The answer is here: How to use C/Cpp extension and add includepath to configurations.
Click the light bulb and then edit the JSON file which is opened. Choose the right block corresponding to your platform (there are Mac, Linux, Win32 – ms-vscode.cpptools version: 3). Update paths in includePath (matters if you compile with VS Code) or browse.paths (matters if you navigate with VS Code) or both.
Thanks to #Francesco Borzì, I will append his answer here:
You have to Left 🖰 click on the bulb next to the squiggled code line.
If a #include file or one of its dependencies cannot be found, you can also click on the red squiggles under the include statements to view suggestions for how to update your configuration.
If you are working with cmake-tools and the error messages says something is wrong with the configurationProvider, then you have 2 options:
Use ms-vscode.cpptools instead of ms-vscode.cmake-tools
Define the headers in CMakeLists.txt
Option 1: Use ms-vscode.cpptools instead of ms-vscode.cmake-tools.
Open c_cpp_properties.json. (windows key on windows or cmd key on mac + shift + p, enter "c/c++ edit configurations" and chose 'json'.
Enter ms-vscode.cpptools as value for configurationProvider instead of ms-vscode.cmake-tools or whatever you have.
How it should look like after the replacement of configurationProvider:
One other important configuration is the include path. The assumption is that you have this configuration right. May be like following
Option 2: Define the headers in CMakeLists.txt
When configurationProvider is set to ms-vscode.cmake-tools in c_cpp_properties.json, VS Code uses the include information defined in the CMakeLists.txt instead of reading the includePath configs in VS Code.
So you need to setup the include path correctly:
using the include_directories command (rather than the target_include_directories command) to define the headers
Configure the project to reflect the change happened in the previous step.
Left mouse click on the bulb of error line
Click Edit Include path
Then this window popup
Just set Compiler path
I ended up here after struggling for a while, but actually what I was missing was just:
If a #include file or one of its dependencies cannot be found, you can also click on the red squiggles under the include statements to view suggestions for how to update your configuration.
source: https://code.visualstudio.com/docs/languages/cpp#_intellisense
The error message "Please update your includePath" does not necessarily mean there is actually a problem with the includePath. The problem may be that VSCode is using the wrong compiler or wrong IntelliSense mode. I have written instructions in this answer on how to troubleshoot and align your VSCode C++ configuration with your compiler and project.
I'm on a Macbook M1 Pro, and I had red squiggly error lines all over my C++ files. To solve, I did this:
Open Preferences -> Settings
Search for intelliSenseEngine
Change "C_Cpp: Intelli Sense Engine" from Default to Tag Parser
alternatively, you could create a .vscode folder in your project root, and then create a settings.json with the content of
{
"C_Cpp.intelliSenseEngine" : "Tag Parser"
}
ideally, you should have a c_cpp_properties.json file in the same folder with the right settings as well.
Note: I got this idea from Github here.
I was trying a hello world program, and this line:
#include <stdio.h>
was underlined green. I tried:
Deleting the line
Re-writing the line
Clicking the yellow bulb and choosing to update
fixed the error warning. i don't know if it fixed the actual problem. But then i'm compiling via a linux VM on Windows 10
Go to your c_cpp_properties.json file by searching from settings.There you might see the following code
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "gnu17",
"cppStandard": "c++17",
"intelliSenseMode": "linux-gcc-x64"
}
],
"version": 4
}
Change the compiler path as below
"compilerPath": "/usr/bin/g++",
After closing and reopening VS, this should resolve.
For Windows:
1.Install Mingw-w64
2.Then Edit environment variables for your account "C:\mingw-w64\x86_64-8.1.0-win32-seh-rt_v6-rev0\mingw64\bin"
3.Reload
For MAC
1.Open search ,command + shift +P, and run this code “c/c++ edit configurations (ui)”
2.open file c_cpp_properties.json and update the includePath from "${workspaceFolder}/**" to "${workspaceFolder}/inc"
If someone have this problem, maybe you just have to install build-essential.
apt install build-essential
For me, using Ubuntu, I just had to install gcc to solve this issue.
sudo apt install gcc
Then, set the compiler path to gcc. Go to your c_cpp_properties.json file, set:
"compilerPath": "/usr/bin/gcc"
An alternative answer would be opening VS Code in remote WSL, if you going to compile files with g++. Just close your VS Code and open WSL and type code . After that the File Explorer shows that VS Code is now running in the context of WSL with the title bar [WSL: Ubuntu]. But make sure you'd installed the GNU compiler tools and the GDB debugger on WSL.
source: https://code.visualstudio.com/docs/cpp/config-wsl
In my case I did not need to close the whole VS-Code, closing the opened file (and sometimes even saving it) solved the issue.
I had luck removing the comments from c_cpp_properties.json in the .vscode folder. Comments aren't permitted in json files by default and you can't simply rename it .jsonc. Referenced In VS Code, disable error "Comments are not permitted in JSON"
My header file was in include/head.h, code in src/code.cpp. I wrote
#include "head.h"
and got this error. Changing it to
#include "../include/head.h"
fixed it.
I solved this problem, once I removed configurationProvider node and set
cStandard and cppStandard to default values:
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}",
"${workspaceFolder}/**",
"${workspaceFolder}/test",
"/opt/qt5/include/QtCore",
"${workspaceFolder}/test"
],
"defines": [],
"compilerPath": "/usr/bin/clang",
"cStandard": "${default}",
"cppStandard": "${default}",
"intelliSenseMode": "linux-clang-x64"
}
],
"version": 4
}
after you install the c/c++ extension, two files are created inside .vscode folder.
open c_cpp_properties.json file and paste this key-value pair inside configuration object.(if it doesn't already exists)
"configurationProvider": "ms-vscode-cpptools"
if it does already exists in the object, see if the value part is ms-vscode-cmaketools. if such it is, replace that existing line with above line.
this will allow you to execute your cpp files along with c files.
I solved the error on my Mac by just clicking on the Edit "include path settings" and changing the compiler path to /usr/bin/clang.
For Windows:
Please add this directory to your environment variable(Path):
C:\mingw-w64\x86_64-8.1.0-win32-seh-rt_v6-rev0\mingw64\bin\
For Include errors detected, mention the path of your include folder into
"includePath": [
"C:/mingw-w64/x86_64-8.1.0-win32-seh-rt_v6-rev0/mingw64/include/" ]
, as this is the path from where the compiler fetches the library to be included in your program.
In case you've copied and pasted code into your new file in VS Code
Please delete #include <iostream> and try to build again.
I really prefer writing code in sublime text or anything else. So, naturally that's what I want to use. However, when I try to open the file in Netbeans, I get an error. So, I want to know how I can save a .cpp file from sublime text and then go about running it through the command prompt. I know I have to set up a path or something, but I'm not exactly sure how to do it. Thanks for any help at all. Also, I am new to C++ and programming in general(have dabbled in Python a bit).
EDIT: Really sorry, I meant how do I actually execute/run the file afterwards. Like if the program were to just print out "Hello World".
The following build system should suit your needs, assuming that you're using the GNU Compiler Collection and g++ for compiling your .cpp files:
{
"cmd": ["g++", "${file}", "-o", "${file_base_name}"],
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "source.c, source.c++",
"variants":
[
{
"name": "Run",
"cmd": ["${file_base_name}"]
}
]
}
Please note that the following instructions are for Sublime Text 2 only...
To use it, select Preferences -> Browse Packages... to open the Packages folder in Windows Explorer. It should be located in C:\Users\YourUserName\AppData\Roaming\Sublime Text 2. Or not, depending on your install. In either case, browse to the C++ directory and open the file C++.sublime-build in Sublime and set the syntax to JSON if you want it to look prettier. Replace its entire contents with the code above, then save the file. The old code is kind of convoluted, and also runs some commands needlessly.
Now, set the build system by going to Tools -> Build System and selecting Automatic. Assuming that g++ is in your PATH, you can build your executable using the CtrlB keyboard shortcut, also available via Tools -> Build. If your binary has already been compiled, you can run it by pressing CtrlShiftB.
One final note: if your program asks for any kind of input, or has a graphical user interface, this Run command won't work. Instead, replace it with the following:
"name": "Run",
"cmd": ["start", "cmd", "/k", "${file_path}/${file_base_name}"],
"shell": true
This will open a new instance of the command line and run your program from there, instead of inside Sublime. The /k switch means that the window will be kept open after your program has run, so you can examine output, errors, etc. If instead you want the window to close immediately, simply change the /k to /c.
Good luck!