Compiling a cpp file with vscode, in Ubuntu - c++

I'm trying to follow this link on how to get started with c++ and vscode in ubuntu.
I have gcc already installed with the latest version.
Running sudo apt-get install build-essential gdb gives:
Reading package lists... Done
Building dependency tree
Reading state information... Done
build-essential is already the newest version (12.8ubuntu1.1).
build-essential set to manually installed.
gdb is already the newest version (9.2-0ubuntu1~20.04.1).
gdb set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.
However, when I get to the stage of creating the config file, I have no option for C/C++: g++ build active file. I only have
So, I choose /usr/bin/cpp.Then I build the file, and get the success message.
However, when run the newly created executable file, I get several error messages:
./helloworld: line 17: namespace: command not found
./helloworld: line 23: syntax error near unexpected token `('
./helloworld: line 23: ` typedef decltype(nullptr) nullptr_t;'
the strange thing is that the lines with code in the helloworld file end on line 16, so I think there's something wrong with the compiler...

Its best to get GCC working in your commandline, then get it working using VS Code tasks.
I suggest that you create the most simplistic project structure you can. Use only a project directory, and a single file named main.cpp.
Something that looks like this:
PROJECT (dir) // path = ./
│
└──> main.cpp (file) // path = ./main.cpp
Once you have a directory with main.cpp do 1 of 2 things:
Use the following command to add a Hello World example to your main.cpp file.
$> echo -e "\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n cout << \"Hello World\!\" << endl;\n}" > main.cpp
Or copy and paste the code below into main.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
}
FYI: You should be doing this from the command-line not vscode (not until you create the vscode task which I will show bellow)
Another thing to note, is your commandline should be pointed to your project directory, the directory you created with main.cpp in it.
From inside your project directory execute the following command.
$> g++ ./main.cpp -o build
if your file compiled & built your executable correctly you should be able to use the ls command to see a new file named build in your project directory.
If all went well, the new build file is an executable. Execute it by entering...
$> ./build
and you should see "Hello World!"
At this point use the following command...
$> code .
VS Code should open to your projects directory.
Now using vscode create another directory, and name it ./.vscode
Then add a file to the ./.vscode directory named tasks.json
The files full pathname will be: ./.vscode/tasks.json
then you will want to add the following to your tasks file
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "GCC: My Compilation Task",
"command": "/usr/bin/g++",
"args": ["-g", "./main.cpp", "-o", "./build"],
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
then you should be able to press F1 and type RUN TASK, when you see the option in the quick menu that says RUN TASK click it, and then select the tasks with the same name as the label key in your tasks.json file, which is "GCC: My Compilation Task"

Related

Windows: fatal error: gtkmm.h: No such file or directory

I'm complety despairing compiling my C++ program using Gtkmm3..
I read about 30 different Stackoverflow, Microsoft and other forum entries but nothing works.
The problems were:
Using vcpkg doesn't work since I need Gtkmm3 not 4.
Using VS Studio fails to generate the cache.
Using VS Code doesn't find gtkmm.h (see error message in the title) although I did EVERYTHING this page told me to do: https://wiki.gnome.org/Projects/gtkmm/MSWindows several times in several folders. And of course I have set the right Path in the Windows settings.
The compiler used (terminal told me) is in: D:\msys64\mingw64\bin\g++.exe
I also edited the launch.json with:
{
"version": "0.2.1",
"tasks": [
{
"taskName": "build-all",
"appliesTo": "example.cpp",
"contextType": "build",
"type": "launch",
"command": "${env.comspec}",
"args": [
"g++ -std=c++17 -o example.exe -g example.cpp simple `pkg-config gtkmm-3.0 --cflags --libs`"
]
}
]
}
I also tried compiling the .exe with Clion with standard CMakeLists.txt I wrote but that doesn't work as well cause Clion can't find either pkgConfig or gtkmm.h.
I tried CodeBlocks with specific Path setting to MinGW.
Someone on StackOverflow wrote a script for installing Gtkmm3 using MinGW in the terminal (Can't find the link for now sorry)... But of course: It didn't work!
So after almost infinity attemps, 4-5 days of trying I gave up now. Hopefully someone can help me here having the same problem.

Visual Studio Code Debug: source and then launch on same shell

My current workflow for a project is the following:
build the project (via catkin)
source a setup.sh script (generated by catkin, which I wouldn't like to modify) setting environment variables and the names needed by my executable.
Run "MyProgram", which is only available after sourcing the "setup.sh" script.
I would like to be able to debug my project in Visual Studio Code. To do this, I have defined a task building the executable via catkin, named "catkin build all", and I have defined a second task as:
{
"type": "shell",
"label": "load programs",
"command": "source /some_folder/setup.sh",
"group": "build",
"dependsOn": ["catkin build all"]
}
Which is the "preLaunchTask" of my lanuch.json launch configuration.
Launching debug will correctly compile the project, but execution fails with error "launch: program myProgram does not exist". Indeed program MyProgram can not be found if setup.sh is not sourced, but is should be sourced by the "preLaunchTask".
In my launch.json i can also set "program" to "/full/path/to/myProgram" instead of "myProgram", but in this case shared libraries are not found, as setup.sh would take care of that.
I have also tried to source setup.sh on a shell and then launch visual studio code from the same shell, but this did not solve the "launch: program myProgram does not exist" problem.
Do tasks run on different shells? How can I have the preLaunchTask running in the same shell as the subsequent program code? Or any other hint on how to get my workflow working?
My solution is to use a env_file
In one terminal, source your file such as: source /opt/ros/melodic/setup.bash
Recover the changes by using: printenv | grep melodic
Create a .env file in your repo with the environment variables; (except PWD)
LD_LIBRARY_PATH=/opt/ros/melodic/lib
ROS_ETC_DIR=/opt/ros/melodic/etc/ros
CMAKE_PREFIX_PATH=/opt/ros/melodic
ROS_ROOT=/opt/ros/melodic/share/ros
PYTHONPATH=/opt/ros/melodic/lib/python2.7/dist-packages
ROS_PACKAGE_PATH=/opt/ros/melodic/share
PATH=/opt/ros/melodic/bin:/home/alexis/.nvm/versions/node/v8.16.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
PKG_CONFIG_PATH=/opt/ros/melodic/lib/pkgconfig
ROS_DISTRO=melodic
Add the following line to your launch.json task: "envFile": "${workspaceFolder}/.env"
Note: this could be automated in a prerunTask using:
command: "source /opt/ros/melodic/setup.bash; printenv | grep melodic > ${workspaceFolder}/.env"
Perhaps this might help after a zoom.
Got that info from here

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

'g++' is not recognized as an internal or external command, operable program or batch file

#include<iostream>
using namespace std;
int main()
{
cout<<"hi"<<endl;
return 0;
}
I am using Sublime text 3, and I am getting this error:
error-
'g++' is not recognized as an internal or external command,
operable program or batch file.
[Finished in 0.0s]
Try to set g++ to your system path.
You can refer to this:
http://stephencoakley.com/2015/01/21/guide-setting-up-a-simple-c-development-environment-on-windows
I faced the same problem while running the code from command line. And found out that I messed up with MinGW installation. So I reinstalled it,
Do this while installing MinGW ----
After downloading, install MinGW and wait for the “MinGW Installation Manager” to show up.
When the “MinGW Installation Manager” shows up, click on mingw32-gcc-g++ then select “Mark for Installation”
In the menu at the top left corner, click on “Installation > Apply Changes”
Wait and allow to install completely. Ensure you have a stable internet connection during this process.
when it is done, then edit the environment 'Path' Variable as stated in other answer.
In short I followed this
For me, it's easily fixed by two steps, as below:
Set the environment variable:
C:/MinGW/bin
Paste the following code in the "launch.json":
{
"version": "0.2.0",
"configurations": [
{
"name": "C++ Compiler",
"type": "cppvsdbg",
"request": "launch",
"program": "C:/MinGW/bin",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true
},
]
}
Open mingw-w64 folder
click on mingw32->i686-w64-mingw32->bin
copy this path and set this path in your system environment variables
If you keep getting this error, make sure you set up MinGW in Path variable, not separated user\system variables: pic link on imgur here
The best thing to do is first of all ensure you have download minGW properly you can refer from this site https://www.msys2.org/ , Be sure to follow all the steps inorder for it to install completely (ps:it takes a while),, after that you can go to environment system variables via settings and a new path C:\msys64\mingw64\bin or wherever your msys64 file might be stored. Hope this helps
Check if you have installed g++ by typing g++ --version. If you already have g++ compiler installed, just hit ctrl + S to save the changes you made, then run the code.

How to build and run c++ programs in Sublime Text 2, Windows 8?

I installed Codeblocks with mingw, chose default compiler, and could build and run a simple hello program without errors.
I installed Sublime Text 2, copy pasted the same hello world program:
// my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
Upon building, I get the error message:
[Error 2] The system cannot find the file specified
[cmd: [u'bash', u'-c', u"g++ '' -o '/' && '/'"]]
[dir: C:\Windows\system32]
[path: C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\]
[Finished]
What do I need to do in order to build and run a simple program using Sublime Text 2?
First, make sure you save the file you're working on, wherever on your drive, before building and running.
Sublime Text 2 needs g++, bash, etc in order to compile. These packages need to be installed on your computer, as per the instructions on this page:
http://mjiang.com/mec/cs244/files/Installing%20c++_g++_on_Windows.pdf
For WINDOWS:
If you have Dev C++ (Bloodshed) then,
OPEN SUBLIME TEXT 2 and creat a new file to write your code (change build system to c++ through Tools> Build System> C++ as SublimeText2 doesn't come with build-system for c)
After that, you save that file to bin folder contained in Dev-Cpp folder and press ctrl+b
If your code is correct (bug free) then you'll found a corresponding file (in .exe format) on same directory which will show you
Hello World!
REMEMBER: SUBLIME TEXT 2 is an Editor, not a COMPILER
You could use my working C++.sublime-build file for Windows:
https://gist.github.com/trietptm/4950038
just create new Build-system (TOOLS->BUILD SYSTEM->NEW BUILD SYSTEM)
{
"windows":
{
"cmd": ["g++", "$file_name","-o", "${file_base_name}.exe", "-lm", "-Wall", "&","start", "${file_base_name}.exe"]
},
"selector": "source.c++",
"shell": true,
"working_dir": "${file_path}"
}
and save it as (name_you_can_provide).sublime-build and use that build system. :)
(I assume you already have installed MingW in your computer.)
You need to go to
Preferences->Browse Packages->C++ folder->C++.sublime-build;
bring this C++.sublime build file into the sublime text editor and now paste this code :
{ "cmd": ["g++", "$file", "-o", "$file_base_name"], "selector": "source.c++", "working_dir": "$file_path", "variants": [ { "name": "Run", "cmd": ["g++", "$file", "-o", "$file_base_name", "&&", "$file_path/$file_base_name"], "shell": true } ]
}
Hope this helps you.
You must install MinGW, then add path to MinGW to PATH variable.