why can't i use gcc on visual studio code? - c++

I have installed g++ on Windows.Later I added the compiler path to the windows 10 environment variables.But how can i add g++ compiler on visual studio code? I tried many guides on youtube but they didn't help me, in fact I can't see the lunch.json file

If you don't already have a task file: Create a task file, so tasks.json in .vscode. If you don't already have one, open the command pallet (it's in view) and type task then press configure task file.
If you do have a task file: Once you have the task file in command type
"command": "{Path to g++.exe}\\g++.exe", with \\ for directories instead of / or \.
Mine is "G:\\Apps\\MinGW\\bin\\g++.exe".
Then, Ctrl+Shift+b in the file you want to compile and press your task file.

Related

Build specific projects with devenv

I have the following folder structure for a VS2019 solution/project:
Solution_folder\
my_solution.sln
cpp_project\
my_cpp_project.vcproj
ifort_project\
my_ifort_project.vfproj
...
...
and I want to build specific projects from this solution using the command prompt.
Following the answer here, as well as the MS docs guidance
I tried the following:
devenv %path_to_sln_folder%\my_solution.sln /build Release /project .\ifort_project\my_ifort_project.vfproj /projectconfig Release
Also tried other variations according to the documentation (eg reference the name of the project only or pass the absolute path of the project). However, I always get the following error:
The operation could not be completed
Use:
devenv [solutionfile | projectfile | folder | anyfile.ext] [switches]
The first argument for devenv is usually a solution file, project file or a folder.
You can also use any other file as the first argument if you want to have the
file open automatically in an editor. When you enter a project file, the IDE
looks for an .sln file with the same base name as the project file in the
parent directory for the project file. If no such .sln file exists, then the
IDE looks for a single .sln file that references the project. If no such single
.sln file exists, then the IDE creates an unsaved solution with a default .sln
file name that has the same base name as the project file.
Command line builds:
devenv solutionfile.sln /build [ solutionconfig ] [ /project projectnameorfile [
/projectconfig name ] ]
Available command line switches:
/Build Builds the solution or project with the specified solution
configuration. For example "Debug". If multiple platforms
are possible, the configuration name must be enclosed in quotes
and contain platform name. For example: "Debug|Win32".
/Clean Deletes build outputs.
/Command Starts the IDE and executes the command.
/Deploy Builds and then deploys the specified build configuration.
/DoNotLoadProjects Opens the specified solution without loading any projects.
/Edit Opens the specified files in a running instance of this
application. If there are no running instances, it will
start a new instance with a simplified window layout.
/LCID Sets the default language in the IDE for the UI.
/Log Logs IDE activity to the specified file for troubleshooting.
/NoVSIP Disables the VSIP developer's license key for VSIP testing.
/Out Appends the build log to a specified file.
/Project Specifies the project to build, clean, or deploy.
Must be used with /Build, /Rebuild, /Clean, or /Deploy.
/ProjectConfig Overrides the project configuration specified in the solution
configuration. For example "Debug". If multiple platforms are
possible, the configuration name must be enclosed in quotes
and contain platform name. For example: "Debug|Win32".
Must be used with /Project.
/Rebuild Cleans and then builds the solution or project with the
specified configuration.
/ResetSettings Restores the IDE's default settings, optionally resets to
the specified VSSettings file.
/ResetSkipPkgs Clears all SkipLoading tags added to VSPackages.
/Run Compiles and runs the specified solution.
/RunExit Compiles and runs the specified solution then closes the IDE.
/SafeMode Launches the IDE in safe mode loading minimal windows.
/Upgrade Upgrades the project or the solution and all projects in it.
A backup of these files will be created as appropriate. Please
see Help on 'Visual Studio Conversion Wizard' for more
information on the backup process.
Product-specific switches:
/debugexe Open the specified executable to be debugged. The remainder of
the command line is passed to this executable as its arguments.
/diff Compares two files. Takes four parameters:
SourceFile, TargetFile, SourceDisplayName(optional),
TargetDisplayName(optional)
/TfsLink Opens Team Explorer and launches a viewer for the
provided artifact URI if one is registered.
/useenv Use PATH, INCLUDE, LIBPATH, and LIB environment variables
instead of IDE paths for VC++ builds.
To attach the debugger from the command line, use:
VsJITDebugger.exe -p <pid>
I must say that just by removing the part from /project onwards, the build starts ok and finishes without errors, but it is not what I want.
It strikes me as odd, as I believe I'm following the documentation correctly, yet the error message suggests I don't? Also, it doesn't seem to be solution- or project-specific as it's happening with other solutions/projects.
Am I missing anything obvious here?
Thanks

Visual Studio Code creates the executable file outside of the intended folder

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.

VS code: Useless file keep appearing

Visual Studio Code 1.46.1
Operating system: MacOS 10.15.4 (Catalina)
VS Code Package used: C/C++, Code Runner
Problem: When I run a C++ code using Code Runner, a file with no extension automatically appear.
I would like to know what does this 'useless file' do, and how to make these files stop from spawning.
That is the executable file also called binary file. They are the executable like .exe in windows so it is very useful(as it is the output of source code). If you dont want to see that file in sidebar of vscode then there is a good answer to this question. Alternatively you can configure your build configuration file (located at .vscode in you working directory) and set the build path to somewhere else
You are using Code Runner extension on vscode then you can modify the execution command.
Go to Code-runner: Executor Map Setting
I did this:
"code-runner.executorMap": {
...
"c": "cd $dir && gcc $fileName -o ./temp/$fileNameWithoutExt && $dir./temp/$fileNameWithoutExt",
...
}
create a temp folder.
Now your temp folder will contain those unwanted files.
You can modify execution command like this for c++ also.

Where should i save codeblocks projects?

so i downloaded codeblocks codeblocks-13.12mingw-setup-TDM-GCC-481.exe
when i try to run main.cpp i get this error message:
Failed to open 'C:\Users\$imba\Documents\Codeblocks projects\test\main.cpp'.
this is a detailed summary of what i did prior to opening main.cpp
i selected the defaults all the way through the end. I created a seperate folder (called Codeblocks projects) in my documents to save the projects in.
now when i went to create a new folder, i selected console application, C++ and then i named my project test. i decided to create the project in the Codeblocks projects folder that i created. the resulting filename comes out to be C:\Users\$imba\Documents\Codeblocks projects\test\test.cbd
i then selected
GNU GCC Compiler,
'Create Debug Configuration: Debug'
output dir: bin\Debug\
object dir.: obj\Debug\
i selected create Release configuration,: 'Release'
output dir.: bin\release\
objects output dir.: obj\ Release
Finish
when i double click on main.cpp is when i get the error message
Failed to open 'C:\Users\$imba\Documents\Codeblocks projects\test\main.cpp'.
please help, i need this program for my course.
Try saving it in a folder in C:\, like C:\Cpp\. Code::Blocks may be having problems with the space or the $ in the file path.
I just created a new folder CB-Project under my D: drive where I have codeblocks installed.
You may want to look in the directory that you have CB installed in first, you may also find this in program file (x86) or the codeblocks sub directory. Look for a file named that may have proj or project in it's name. If you don't find it you can just create a new folder. You will have to put the new folder name in the CB path so it will find it.

How can I capture the cl.exe command line in Visual Studio 2010?

I have a project that I converted from a makefile that has a source file that expects the command line options from the compiler. For example for when the project was built with gcc if you did program --help it would spit out the gcc command line used to compile the program.
How can I do the same thing in Visual Studio, so that it spits out the cl command line used to compile the program? Basically I want to hit F7 (to build solution) and have the whole thing automated. I can't find a macro for it. Thanks
edit; I mean programatically, so for example I want when I run the program for its output to contain the cl.exe command string that is used. You can see the command line at Configuration Properties > C/C++ > Command Line > All Options but I can't find a macro for it or some way to encapsulate it in a file.
Since VS switched the underlying build system to MsBuild the command line as shown in that dialog is created programatically within VS only. It might not even be the exact command line passed to cl: MsBuild itself invokes CL via a task and as such there is no direct link with what is shown in VS nor is there a way to get the command line out of it.
Anyway, there is no such thing as the command line since each source file might have different options. Furthermore I doubt you want the full commandline including the absolute include paths etc. Nobody is interested in that. Now if you make clever use of the macros from http://msdn.microsoft.com/en-us/library/b0084kay.aspx you can sort of recreate the command line yourself since most options are there:
std::string CompilerCommandLineOptions()
{
std::string cmd;
#ifdef _CHAR_UNSIGNED
cmd += " /J";
#endif
#ifdef __cplusplus_cli
cmd += " /clr";
#endif
#ifdef _CPPRTTI
cmd += " /GR"
#endif
//etc
return cmd;
}
Note: are you sure it's worth the hassle? Is there really somebody interested in the command line? It's not even sufficient to build the project. Why not the linker options as well then?
A .vcxproj is a Visual Studio project in the MSBuild project format. You can build it by running msbuild.exe, devenv.exe, devenv.com, using the Visual Studio GUI or the MSBuild API.
Visual Studio GUI uses the MSBuild API. In doing so, it limits the MSBuild output.
If you want more details, change your user settings in Visual Studio:
Tools > Options > Project and Solutions > Build and Run > two verbosity settings
Detailed will show the cl.exe command lines.
The closest thing which I came across cl command line which msuild executes is "hacking" the rsp file used while calling cl.exe.
Using Override compiler solution, I changed ClCompile ToolExe to custom mycl.bat script and this script received an argument which was #tmp-1234xxx.rsp file. This rsp file contained whole command line except cl.exe path, something like -
rsp file
/P /DDEBUG Source.cpp
Then after making desired changes in the rsp file by calling a separate bash script which were very minor for me, I called cl.exe with contents of my rsp file. So, whenever user hits the build button, this script executes.
mycl.bat script
#echo off
SET PATH=%PATH%;/usr/bin //to call cygwin bash
set parameter=%1
set parameter=%parameter:~1% //to remove # in the beginning
c:/cygwin/bin/bash process.sh %parameter%
process.sh
iconv -f UCS-2 -t UTF-8 <$1 >$1.conv //file converted to UTF-8, else bash wasn't handling it well
contents=`cat $1.conv`
#Processing on file contents here
path/to/cl.exe $(contents)
Very nasty solution, but it worked for my use case. I wanted to change the names of the file on the go based on some logic.
The problem I faced is Visual Studio uses tlogs written by CL Task to check while file needs to to be rebuilt on incremental build and my target's tlogs files were not enough. There were tlogs of every command in batch and bash scripts but not for whole target. So, it was building whole thing on incremental builds also.