Configuring Visual studio code for c++ - c++

I am facing issues in configuring VS code on mac for running c++ programs. I have already created the 3 files for setup- 1.c_cpp_properties 2.launch.json . 3.tasks.json. Please let me know the issue in the 3 json files i have added . I am getting error in my terminal-
Executing task: clang++ -std=c++17 -stdlib=libc++ vectors.cpp -o vectors.out --debug <
clang: error: no such file or directory: 'vectors.cpp'
clang: error: no input files
The terminal process command '/bin/bash -c 'clang++ -std=c++17 -stdlib=libc++ vectors.cpp -o vectors.out --debug'' failed to launch (exit code: 1)
/*Contents of 1st file:*/
{
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"macFrameworkPath": [
"/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks"
],
"compilerPath": "/usr/bin/clang",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}
/*contents of 2nd file:*/
{
// 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": "(lldb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "/Users/tanvi.singh/Documents/quest/learn_ds/vectors.out",
"args": [],
"stopAtEntry": true,
"cwd": "/Users/tanvi.singh/Documents/quest/learn_ds/",
"environment": [],
"externalConsole": true,
"MIMode": "lldb",
"logging": {
"trace": true,
"traceResponse": true,
"engineLogging": true
}
}
]
}
/* contents of 3rd file:*/
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Build with Clang",
"type": "shell",
"command": "clang++",
"args": [
"-std=c++17",
"-stdlib=libc++",
"vectors.cpp",
"-o",
"vectors.out",
"--debug"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

All you need to do is create a file.cpp and save it somewhere.
You can use
#include <iostream>
using namespace std;
int main()
{
cout << "hello world" << endl;
return 1;
}
Then you will want to open a terminal with 'command' + 'space' this will pull up the stoplight search. Search terminal and open. Type
g++ into terminal and hit enter, it may prompt you to install some things just agree to it and it will install the compiler.
Once that is installed you can type into the terminal g++ filename.cpp
In order for this to work you will need to cd into the correct directory, or you can type the 'g++ ' part and then just drag in the filename.cpp file and it will automatically add in the files path. Enter.
You should see that an a.out file was created. To run the code, type ./a.out into the terminal or if you are not in the correct directory then ./ then drag the a.out file into terminal to paste the path. Enter. You should see the terminal print 'hello world'
I do assume you wanted to run the code with a terminal as there is not much other options for vs code on mac unless you want to use makefiles or cmake. If you would like to learn more about the terminal or makefiles (which are amazing), I can help with that too.

Related

Building a wxWidgets project in VS Code

I try to start using Linux(Fedora 33) and now I've got a trouble. I want to use VS Code and it builds simple cpp projects correctly, but I want to make GUI using wxWidgets. So I created simple example, but it doesn't want to build it. I installed wxWidgets from rpm package. I also added pathes into includePath in configuration file. Now I want to show you the code and errors.
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
int main() { return 0; }
tasks.json
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ сборка активного файла",
"command": "/usr/bin/g++",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "компилятор: /usr/bin/g++"
}
],
"version": "2.0.0"
}
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "g++ - Сборка и отладка активного файла",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Включить автоматическое форматирование для gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: g++ сборка активного файла",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
c_cpp_properties.json
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"/usr/include/**",
"/usr/lib64/wx/include/**"
],
"defines": [],
"compilerPath": "/usr/bin/clang++",
"cStandard": "c17",
"cppStandard": "c++14",
"intelliSenseMode": "linux-clang-x64",
"compilerArgs": []
}
],
"version": 4
}
Now, there are no errors given me by intellisence, I think.
Compilers errors:
Запуск сборки…
/usr/bin/g++ -g /home/nikita/Workfiles/wxex/main.cpp -o /home/nikita/Workfiles/wxex/main
/home/nikita/Workfiles/wxex/main.cpp:1:10: фатальная ошибка: wx/wxprec.h: Нет такого файла или каталога
1 | #include <wx/wxprec.h>
| ^~~~~~~~~~~~~
компиляция прервана.
Сборка завершена с ошибками.
The terminal process failed to launch (exit code: -1).
Replace
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
with
#include <wx/wx.h>
wxWidgets provides wx-config script under Unix which must be used to obtain the options necessary for compiling and linking programs using the library. Please run wx-config --cxxflags to obtain the full flags you need to put in your c_cpp_properties.json and also wx-config --libs to get the linker flags that you will need to use to make the program link, and not just compile, successfully.
As the person who starts using Linux AND wants to learn new library id recommend followinh:
Grab the source code from www.wxwidget.org/download
Unpack it somewhere
Open the terminal
cd wxWidgets-3.1.4
mkdir buildGTK
cd buildGTK
../configure --enable-debug
make
cd samples/minimal
Make
Now the last make command will display everything you need to include and link against. You will also have a samples code you can refer to when needed.
If you don't want to build the library from source - try the following
Open terminal
Type "which wx-config" (without quotes) and press ebter
Run "/path/to/wx-config --cxxflags" (without quots)
Run "/path/to/wx-config --libs" (without quotes)
Use the output from the commands above in you IDE.
HTH.

vscode clang++: no such file or directory: 'main.cpp'

Okay, so this is terribly frustrating.
I am simply trying to using clang++ in my VSCode editor to compile a very simple main.cpp program, located in the 'main' module of my project.
The project hierarchy is as follows:
${workspaceFolder}/
cpp/
main/
main.cpp
There are many other folders and files that I have purposefully omitted for the sake of simplicity.
Here is my terminal output from my tasks.json build task:
> Executing task: clang++ -Wall -std=c++17 -stdlib=libc++ -o main.out main.cpp -I/Users/ajm/Projects/restaurant/cpp/main/ --debug <
clang: error: no such file or directory: 'main.cpp'
clang: error: no input files
The terminal process terminated with exit code: 1
main.cpp is clearly in the folder that I am trying to include with -I (see the following screenshot):
What the heck am I missing here??? I am very tempted to switch my C++ IDE to either Visual Studio or Xcode, as besides this issue, VSCode's C++ autocomplete is buggy and terribly slow.
Note that I am new to using clang++. I have read through 5-10 other SO posts of others going through similar issues, none of which have helped. I also haven't found anything helpful on Clang quickstart guides on LLVM or Microsoft's website.
If anyone needs more info to answer the question, just let me know.
Someone, please help! Thanks in advance.
EDIT:
I figured I would also include my tasks.json, c_cpp_properties.json, and launch.json files.
tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"label": "Build with Clang",
"type": "shell",
"command": "clang++",
"args": [
"-Wall",
"-std=c++17",
"-stdlib=libc++",
"-o",
"main.out",
"main.cpp",
"-I${workspaceFolder}/cpp/main/",
"--debug"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
c_cpp_properties.json:
{
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**",
"/usr/local/boost_1_71_0"
],
"defines": [],
"macFrameworkPath": [
"/System/Library/Frameworks",
"/Library/Frameworks"
],
"compilerPath": "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "${default}",
"browse": {
"path": []
}
}
],
"version": 4
}
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": "(lldb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "enter program name, for example ${workspaceFolder}/main.out",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "lldb",
"logging": {
"trace": true,
"traceResponse": true,
"engineLogging": true
}
}
]
}

How to configure VSCode for GTK3 for intellisense / build / debug and g++

I'm using
g++
GTK3
VSCode
How do I get the following to work:
Intellisense / code completion for gtk
Buiding inside VSCode
Debugging with VSCode
Problem:
VSCode does not find includes - especially #include <gtk/gtk.h> is red in source.
The important thing to note is, that you need to tell VSCode the include paths and compiler flags to work properly.
First step: Open the target folder in VSCode.
Now you should have a new hidden folder .vscode in there. Open it.
You want to apply the output of pkg-config --cflags gtk+-3.0 and pkg-config --libs gtk+-3.0 to their respective configs.
Make intellisense / code completion work
Create a file .vscode/c_cpp_properties.json.
Add the following content.
{
"env": {
"myDefaultIncludePath": [
"${workspaceFolder}",
"${workspaceFolder}/include"
],
"myCompilerPath": "/usr/local/bin/g++"
},
"configurations": [
{
"name": "include paths",
"intelliSenseMode": "g++-8",
"includePath": [
"/usr/include/gtk-3.0",
"/usr/include/at-spi2-atk/2.0",
"/usr/include/at-spi-2.0",
"/usr/include/dbus-1.0",
"/usr/lib/x86_64-linux-gnu/dbus-1.0/include",
"/usr/include/gtk-3.0",
"/usr/include/gio-unix-2.0",
"/usr/include/cairo",
"/usr/include/libdrm",
"/usr/include/pango-1.0",
"/usr/include/harfbuzz",
"/usr/include/pango-1.0",
"/usr/include/fribidi",
"/usr/include/atk-1.0",
"/usr/include/cairo",
"/usr/include/pixman-1",
"/usr/include/freetype2",
"/usr/include/libpng16",
"/usr/include/gdk-pixbuf-2.0",
"/usr/include/libmount",
"/usr/include/blkid",
"/usr/include/uuid",
"/usr/include/glib-2.0",
"/usr/lib/x86_64-linux-gnu/glib-2.0/include"
],
"compilerPath": "/usr/local/bin/g++",
"cStandard": "c11",
"cppStandard": "c++17",
"browse": {
"path": [
"${workspaceFolder}"
],
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
}
}
],
"version": 4
}
Note, that the content of "includePath" is the output of pkg-config --cflags gtk+-3.0 without the preceeding -Is and with double quotes and commas. You may have to adjust the values according the output of your machine
Make building work
You want to create a new task inside .vscode/tasks.json with the following content:
{
"type": "shell",
"label": "gcc debug build active file - with GTK",
"command": "/usr/bin/gcc",
"args": [
"-g",
"-pthread",
"-I/usr/include/gtk-3.0",
"-I/usr/include/at-spi2-atk/2.0",
"-I/usr/include/at-spi-2.0",
"-I/usr/include/dbus-1.0",
"-I/usr/lib/x86_64-linux-gnu/dbus-1.0/include",
"-I/usr/include/gtk-3.0",
"-I/usr/include/gio-unix-2.0",
"-I/usr/include/cairo",
"-I/usr/include/libdrm",
"-I/usr/include/pango-1.0",
"-I/usr/include/harfbuzz",
"-I/usr/include/pango-1.0",
"-I/usr/include/fribidi",
"-I/usr/include/atk-1.0",
"-I/usr/include/cairo",
"-I/usr/include/pixman-1",
"-I/usr/include/freetype2",
"-I/usr/include/libpng16",
"-I/usr/include/gdk-pixbuf-2.0",
"-I/usr/include/libmount",
"-I/usr/include/blkid",
"-I/usr/include/uuid",
"-I/usr/include/glib-2.0",
"-I/usr/lib/x86_64-linux-gnu/glib-2.0/include",
"${file}",
"-lgtk-3",
"-lgdk-3",
"-lpangocairo-1.0",
"-lpango-1.0",
"-latk-1.0",
"-lcairo-gobject",
"-lcairo",
"-lgdk_pixbuf-2.0",
"-lgio-2.0",
"-lgobject-2.0",
"-lglib-2.0",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
Note the two more indented parts within args.
The top one is again the output of pkg-config --cflags gtk+-3.0. (This time with the -Is, though.)
The bottom part is the output of pkg-config --libs gtk+-3.0 (quoted and commated)
You might need to adjust these values as well, according to the actual output of the commands on your machine
Make debugging work
You want to create a new configuration inside the .vscode/launch.json file. On my setup vscode kept using the wrong configuration, so I deleted the others. Below is the full content of the file with only one configuration.
{
// 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": "debug with gdb (no build)",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${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": "",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
how about using
"`pkg-config --cflags --libs gtk4`"
note the
`pkg-config`
between pkg-config, it is diferent from
'pkg-config'
to see the full file, here's the gist I've uploaded my tasks.json and c_cpp_properties.json files https://gist.github.com/KesunyianAyam/48810a1f4339f496e192f4e94adc6e3b
mine is gtk4 though, but it can be used for gtk3 by using
`pkg-config --cflags --libs gtk+-3.0`
and use the includes associated with gtk3

Program 'main.exe' failed to run: The specified executable is not a valid application for this OS platform

“I’m setting up Visual Studio Code, and when I try to run my main.cpp (main.exe when executed), It is showing the error mentioned above.
From what I read about the issue online. I think it is because of wrong written in the c_cpp_properties.json file. But I can't figure out where to make the changes.
#Code:
#include <iostream>
int main()
{
std::cout<<"Hello World"<<std::endl;
}
#c_cpp_properties.json :
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"compilerPath": "C:\\MinGW\\bin\\gcc.exe",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64",
"browse": {
"path": [
"${workspaceRoot}",
"C:\\MinGW\\lib\\gcc\\mingw32\\8.2.0\\include\\c++"
],
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
}
}
],
"version": 4
}
Error Message:
Program 'main.exe' failed to run: The specified executable is not a valid application for this OS platform.At line:1 char:1
+ .\main.exe+ ~~~~~~~~~~.
+ FullyQualifiedErrorId : NativeCommandFailed
You're getting this error because you're building on 64 bit windows machine with 32bit cpp.exe. So you're building for a different target machine.
To fix this, change your tasks.json file to point to g++.exe instead of cpp.exe.
To access your tasks.json file on windows (ctrl+shift+p) and then type "tasks"
change cpp.exe to g++.exe
I, too, faced the same error but rectified it with a simple solution
1.) First go and check your extensions whether you have installed the C/C++ by Microsoft.
2.) If not, do that first!
3.) If you have already installed, don't worry, check the version of your Visual Studio Code by clicking help in the menu bar and pressing About.
For version 2.0.0:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Build",
"type": "shell",
"command": "g++",
"args": [
"-o",
"main",
"-g",
"main.cpp"
],
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "Run",
"type": "shell",
"command": ".\\main",
"problemMatcher": []
}
]
}
For version 1.0.0:
{
"version": "0.1.0",
"command": "make",
"isShellCommand": true,
"tasks": [
{
"taskName": "Makefile",
// Make this the default build command.
"isBuildCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "always",
// Pass 'all' as the build target
"args": ["all"],
// Use the standard less compilation problem matcher.
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
4.) Check your version properly and paste the above-mentioned syntax in your tasks.json.
To go to tasks.json Do the following steps:
Press Ctrl+Shift+P.
You will see your command palette where you must type configure tasks. And select (“Tasks: Configure Task”).
You can type the above-mentioned syntax with respect to your Visual Studio Code Version.
Don't miss out the ending curly braces mentioned below the syntax
For me you just need to configure your task.json file
My tasks.json file is this:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Build",
"type": "shell",
"command": "g++",
"args": [
"-o",
"main",
"-g",
"main.cpp"
],
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "Run",
"type": "shell",
"command": ".\\main",
"problemMatcher": []
}
]
}
Also to run the exe file the command is ".\filename" without the extension.
We can execute cpp Programs using
g++ name_of_file.cpp
./a
Or for c prgrams
gcc name_of_file.c
./a

VS Code will not build c++ programs with multiple .ccp source files

Note that I'm using VS Code on Ubuntu 17.10 and using the GCC Compiler.
I'm having trouble building a simple program which makes use of additional .ccp files. I'm probably missing something obvious here as I'm fairly new to programming but I'll explain what I've done so far. This is something that is stopping me from continuing with a tutorial I'm doing.
I have written a very simple program to demonstrate my point as follows.
main.ccp
#include <iostream>
#include "Cat.h"
using namespace std;
int main ()
{
speak();
return 0;
}
Cat.h
#pragma once
void speak();
Cat.ccp
#include <iostream>
#include "Cat.h"
using namespace std;
void speak()
{
std::cout << "Meow!!" << std::endl;
}
This simple program builds in both Codeblocks and Visual Studio Community 2017 no problem and I can't figure out what I need to do to make it run.
This error at the bottom indicates that the Cat.ccp file is not being picked up at all. If I was to drop the definition from this Cat.ccp into the header file the program compiles and runs fine but I need to make use of that .ccp file as I understand this is the accepted way of separating code. I'll note that all the files are in the same folder too.
I understand that I may need to tell VS Code where to look for the Cat.ccp file but it's strange to me that it finds the header in the same location. Nevertheless, after looking online I've been reading that I may need to place a directory into the c_cpp_intellisense_properties.json. Here's what mine looks like.
{
"configurations": [
{
"name": "Mac",
"includePath": [
"/usr/include",
"/usr/local/include",
"${workspaceRoot}"
],
"defines": [],
"intelliSenseMode": "clang-x64",
"browse": {
"path": [
"/usr/include",
"/usr/local/include",
"${workspaceRoot}"
],
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
},
"macFrameworkPath": [
"/System/Library/Frameworks",
"/Library/Frameworks"
]
},
{
"name": "Linux",
"includePath": [
"/usr/include/c++/7",
"/usr/include/x86_64-linux-gnu/c++/7",
"/usr/include/c++/7/backward",
"/usr/lib/gcc/x86_64-linux-gnu/7/include",
"/usr/local/include",
"/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed",
"/usr/include/x86_64-linux-gnu",
"/usr/include",
"/home/danny/Documents/C++_Projects/24_-_Classes/Cat.cpp",
"${workspaceRoot}",
"/home/danny/Documents/C++_Projects/24_-_Classes/",
"/home/danny/Documents/C++_Projects/24_-_Classes/.vscode",
"/home/danny/Documents/C++_Projects/24_-_Classes/.vscode/Cat.cpp"
],
"defines": [],
"intelliSenseMode": "clang-x64",
"browse": {
"path": [
"/usr/include/c++/7",
"/usr/include/x86_64-linux-gnu/c++/7",
"/usr/include/c++/7/backward",
"/usr/lib/gcc/x86_64-linux-gnu/7/include",
"/usr/local/include",
"/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed",
"/usr/include/x86_64-linux-gnu",
"/usr/include",
"${workspaceRoot}",
"/home/danny/Documents/C++_Projects/24_-_Classes/",
"/home/danny/Documents/C++_Projects/24_-_Classes/.vscode/Cat.cpp"
],
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
}
},
{
"name": "Win32",
"includePath": [
"C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include",
"${workspaceRoot}"
],
"defines": [
"_DEBUG",
"UNICODE"
],
"intelliSenseMode": "msvc-x64",
"browse": {
"path": [
"C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include/*",
"${workspaceRoot}"
],
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
}
}
],
"version": 3
}
At one point I wondered if I need to add a double command in there to tell the compiler to build both .ccp files in the tasks.json but I haven't managed to figure out how to do that, or even if that's the right approach.
tasks.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Build",
"type": "shell",
"command": "g++ -g /home/danny/Documents/C++_Projects/24_-_Classes/main.cpp -o Classes",
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher":"$gcc"
}
]
}
Appreciate any help. And just in case you're wondering, the reason I don't just finish the tutorial in Codeblocks or VS Community is that I like to know what's going on under the hood in most things. Plus I'd like to get VS Code working for me as it's been great so far.
in tasks.json:
"label": "g++.exe build active file",
"args": [
"-g",
"${fileDirname}\\**.cpp",
//"${fileDirname}\\**.h",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe",
],
in launch.json:
"preLaunchTask": "g++.exe build active file"
it will work if your sources are in separated folder
feeling lazy,
This is tasks.json of vscode for linux distros, to compile multiple cpp files.
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-g",
"${fileDirname}/*.cpp",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
This is a Windows answer for the same problem:
I was struggling with this as well until I found the following answer at https://code.visualstudio.com/docs/cpp/config-mingw :
You can modify your tasks.json to build multiple C++ files by using an argument like "${workspaceFolder}\\*.cpp" instead of ${file}. This will build all .cpp files in >your current folder. You can also modify the output filename by replacing "${fileDirname}\\${fileBasenameNoExtension}.exe" with a hard-coded filename (for >example "${workspaceFolder}\\myProgram.exe").
Note that the F in workspaceFolder is capitalized.
As an example, in my tasks.json file in my project, the text in between the brackets under "args" originally appeared as follows:
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
This gave me reference errors because it was only compiling one and not both of my files.
However, I was able to get the program to work after changing that text to the following:
"-g",
"${workspaceFolder}\\*.cpp",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
If you have multiple files and one depends on a cpp file for another, you need to tell g++ to compile it as well, so the linker can find it. The simplest way would be:
$ g++ Cat.cpp main.cpp -o Classes
As a side note, you should probably compile with warnings, minimally -Wall, likely -Wextra, and possibly -Wpedantic, so you know if something you're doing is problematic.
After finding a lot of solutions I find this only working,
install the code runner extension. in settings,
go to open settings in the right upper corner
and simply paste this line in setting.json before the end of last closing bracket }
"code-runner.executorMap": {
"cpp": "cd $dir && g++ *.cpp -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
},
[settings.json --> file looks like]
: https://i.stack.imgur.com/pUBYU.png
"tasks": [
{
"label": "echo",
"type": "shell",
"command": "g++",
"args":[
"-g","main.cpp","cat.cpp"
],
"group": {
"kind": "build",
"isDefault": true
}
}
Just add cat.cpp in args and then try to run. It should run without error on VS code
On Windows the solution is
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: cl.exe compila il file attivo",
"command": "cl.exe",
"args": [
"/Zi",
"/EHsc",
"/nologo",
"/Fe:",
"${fileDirname}\\${fileBasenameNoExtension}.exe",
"*.c"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$msCompile"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "compilatore: cl.exe"
}
]
}
On the terminal tab of your VS Code program write the following:
$ g++ nameOne.cpp nameTwo.cpp -o a.out
$ ./a.out
For Mac you can use
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "shell: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-g",
"-Wall",
"-Wextra",
"-Wpedantic",
"${workspaceFolder}/*/*.cpp",
"${fileDirname}/*.cpp",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
This will compile all the cpp file with all the directories which contain .cpp files.
credits: Anns98.
Remember below args are belongs to g++.10.2.0 C++17.
You should tweak your compiler implicitly/explicitly to achieve the consistency you desire.
CHECKOUT:
winlibs (gcc-10.2.0-llvm-11.0.0-mingw-w64-8.0.0-r5) looks promising.
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "retr0C++",
"command": "C:\\mingw64\\bin\\g++",
"args": [
"-std=c++17",
"-I",
"${fileDirname}\\includes",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe",
"-g",
//"${file}",
"${fileDirname}\\**.cpp"
],
"options": {
"cwd": "C:\\mingw64\\bin"
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "compiler: C:\\mingw64\\bin\\g++"
}
]
}
As I understand, your program 24_-_Classes architecture just shows like:
24_-_Classes
|
|_.vscode
| |__c_cpp_properties.json
| |__launch.json
| |__settings.json
| |__tasks.json
|__cat.cpp
|__cat.h
|__main.cpp
Bro, I know what you mean "I understand that I may need to tell VS Code where to look for the Cat.cpp file but it's strange to me that it finds the header in the same location. ".
c_cpp_properties.json: allows you to change settings such as the path to
the compiler, include paths.
As your project architecture shows, your include file is located in the same directory of your source files.
So your c_cpp_properties.json should be looks like:
{
"configurations": [
{
"name": "Mac",
"includePath": [
// This is the include files directory
"${workspaceFolder}/**", // Have Change
"/Library/Developer/CommandLineTools/usr/include",
"/Library/Developer/CommandLineTools/usr/lib/clang/9.0.0/include",
"/usr/local/include",
"/Library/Developer/CommandLineTools/usr/include/c++/v1",
"/usr/include"
],
"defines": [],
"macFrameworkPath": [
"/System/Library/Frameworks",
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks",
"/Library/Frameworks"
],
"compilerPath": "/usr/bin/clang",
"cStandard": "c11",
"cppStandard": "c++11",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}
Notice that line ""${workspaceFolder}/**", // Have Change", as my
comment"// This is the include files directory" shows, change your
""${workspaceRoot}"," to my ""${workspaceFolder}/**".(This is used to add include file directory.)
Change this configuration to your needed Linux. E.g:
{
"configurations": [
{
"name": "Linux",
"includePath": [
// This line is to add include file directory.
"${workspaceFolder}/**" //Needed to Notices!
"/usr/include/c++/7",
"/usr/include/x86_64-linux-gnu/c++/7",
"/usr/include/c++/7/backward",
"/usr/lib/gcc/x86_64-linux-gnu/7/include",
"/usr/local/include",
"/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed",
"/usr/include/x86_64-linux-gnu",
"/usr/include",
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}
There is no need to add that lines:
"/home/danny/Documents/C++_Projects/24_-_Classes/Cat.cpp",
"/home/danny/Documents/C++_Projects/24_-_Classes/",
"/home/danny/Documents/C++_Projects/24_-_Classes/.vscode",
"/home/danny/Documents/C++_Projects/24_-_Classes/.vscode/Cat.cpp"
And I also know what your want to know"At one point I wondered if I need to add a double command in there to tell the compiler to build both .cpp files in the tasks.json",
Your tasks.json just looks like:
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "Compile With clang++",
//"command": "clang++",/usr/bin/clang++
"command": "/usr/bin/clang++",
"args": [
"-std=c++11",
"-stdlib=libc++",
// My project fitBodyBootCamp were under
// /Users/marryme/VSCode/CppProject/fitBodyBootCamp
// So ${workspcaeFolder} also were
// /Users/marryme/VSCode/CppProject/fitBodyBootCamp
// all the *.cpp files were under
// /Users/marryme/VSCode/CppProject/fitBodyBootCamp
"${workspaceFolder}/*.cpp", // Have changed
"-o",
// Thanks those chiense website bloggers!
// 1.mac vscode compile c++ multi-directory code demo
// https://blog.csdn.net/fangfengzhen115/article/details/121496770?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-4.pc_relevant_default&spm=1001.2101.3001.4242.3&utm_relevant_index=7
// 2.Compile and debug c++ multi-folder project under VSCode (non-makefile)
// https://blog.csdn.net/BaiRuichang/article/details/106463035
// I also put the main.o under my current workspace directory
// This after "-o" is the target file test.o or test.out or test
"${workspaceFolder}/${fileBasenameNoExtension}", // Have changed
"-I",
// This after "-I" if the include files directory
"${workspaceFolder}", // Have changed
"-Wall",
"-g"
],
"options": {
// "cwd" is the source files directory
"cwd": "${workspaceFolder}" // Have changed
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
That line I add a comment "//Have changed" that's what you need to notice.
Notices: your source files are not only, that are multiple sources.
So, just use using an argument like "${workspaceFolder}/*.cpp" instead of ${file}.
Also, just use using an argument like
"${workspaceFolder}/${fileBasenameNoExtension}" instead of "${fileDirname}/${fileBasenameNoExtension}".
Change this configuration to your needed Linux, e.g:
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-g",
"${workspaceFolder}/*.cpp", // Need to change!
"-o",
"${workspaceFolder}/${fileBasenameNoExtension}" // Need to change!
],
"options": {
// If This not work, just change to ""cwd": "${workspaceFolder}""
"cwd": "/usr/bin" //I do not if change in Linux!
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
And your launch.json just looks like:
{
// 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": "Debug With LLDB",
"type": "lldb",
"request": "launch",
// "program" is the target file diretory
"program": "${workspaceFolder}/${fileBasenameNoExtension}", // Have changed
"args": [],
"stopAtEntry": true,
//"cwd": "${workspaceFolder}/../build",// Have changed
//"cwd": "${fileDirName}", ${workspaceFolder}/../build
// Changes the current working directory directive ("cwd") to the folder
// where main.cpp is.
// This "cwd" is the same as "cwd" in the tasks.json
// That's the source files directory
"cwd": "${workspaceFolder}", // Have changed
"environment": [],
"externalConsole": false,
"preLaunchTask": "Compile With clang++"
}
]
}
Change this configuration to your needed Linux, e.g:
{
"version": "0.2.0",
"configurations": [
{
"name": "g++ build and debug active file",
"type": "cppdbg",
"request": "launch",
// "program" is the target file diretory
"program": "${workspaceFolder}/${fileBasenameNoExtension}", // Have changed
"args": [],
"stopAtEntry": false,
// That's the source files directory
"cwd": "${workspaceFolder}", // Notices!!!
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "g++ build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
If you are using Code-Runner to run your project, settings.json looks like:
{
"files.defaultLanguage": "c++",
"editor.suggest.snippetsPreventQuickSuggestions": false,
"editor.acceptSuggestionOnEnter": "off",
"code-runner.runInTerminal": true,
"code-runner.executorMap": {
// 0.Only One Simple C/C++ file build, compile, debug...
//"c": "cd $dir && gcc -std=c11 -stdlib=libc++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
//"cpp": "cd $dir && g++ -std=c++11 -stdlib=libc++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"
//"c": "cd $dir && make && ./fileNameWithoutExt && make clean",
//"cpp": "cd $dir && make && ./fileNmaeWithoutExt && make clean"
// "c": "cd $dir && make main && ../build/main && make clean",
// "cpp": "cd $dir && make main && ../build/main && make clean"
// 1.0 Reference
// Thanks chinese website blogger!
// (Configure multiple c file compilation with vscode on Mac os)
// https://blog.csdn.net/songjun007/article/details/117641162
//"c": "cd $dir && gcc -std=c11 -stdlib=libc++ -I ${workspaceFolder}/inc ${workspaceFolder}/*.c -o ${workspaceFolder}/build/${fileBasenameNoExtension} && $dir$fileNameWithoutExt",
//"cpp": "cd $dir && g++ -std=c++11 -stdlib=libc++ -I ${workspaceFolder}/inc ${workspaceFolder}/*.cpp -o ${workspaceFolder}/build/${fileBasenameNoExtension} && $dir$fileNameWithoutExt"
// 1.1Use gcc or g++
// "c": "cd $dir && gcc -std=c11 -stdlib=libc++ $dir/../src/*.c -o $dir/../build/$fileNameWithoutExt && $dir/../build/$fileNameWithoutExt",
//"cpp": "cd $dir && g++ -std=c++11 -stdlib=libc++ $dir/../src/*.cpp -o $dir/../build/$fileNameWithoutExt && $dir/../build/$fileNameWithoutExt"
//
// clang -g /Users/marryme/VSCode/CppProject/fitBody/src/bank.cpp /Users/marryme/VSCode/CppProject/fitBody/src/main.cpp -o /Users/marryme/VSCode/CppProject/fitBody/build/main
// 1.2Use clang or clang++
//"c": "cd $dir && clang -std=c11 -stdlib=libc++ $dir/../src/*.c -o $dir/../build/$fileNameWithoutExt && $dir/../build/$fileNameWithoutExt",
//"cpp": "cd $dir && clang++ -std=c++11 -stdlib=libc++ $dir/../src/*.cpp -o $dir/../build/$fileNameWithoutExt && $dir/../build/$fileNameWithoutExt"
// 2.Seprated multiple sourece C/C++ files under different folder build, compile, debug...
// if put main.o and debug folder into new directory ./build/
//"c": "cd $dir && clang -std=c11 -stdlib=libc++ $dir/*.c -o $dir/../build/$fileNameWithoutExt && $dir/../build/$fileNameWithoutExt",
//"cpp": "cd $dir && clang++ -std=c++11 -stdlib=libc++ $dir/*.cpp -o $dir/../build/$fileNameWithoutExt && $dir/../build/$fileNameWithoutExt"
// 3.Mutiple sourece C/C++ files under same folder build, compile, debug...
// if put main.o and debug folder into the current directory "./"
"c": "cd $dir && clang -std=c11 -stdlib=libc++ $dir/*.c -o $dir/$fileNameWithoutExt && $dir/$fileNameWithoutExt", // Have changed
"cpp": "cd $dir && clang++ -std=c++11 -stdlib=libc++ $dir/*.cpp -o $dir/$fileNameWithoutExt && $dir/$fileNameWithoutExt" // Have changed
},
"code-runner.saveFileBeforeRun": true,
"code-runner.preserveFocus": false,
"code-runner.clearPreviousOutput": false,
"code-runner.ignoreSelection": true,
"C_Cpp.clang_format_sortIncludes": true,
"editor.formatOnType": true,
"clang.cxxflags": [
"-std=c++11"
],
"clang.cflags": [
"-std=c11"
],
"C_Cpp.updateChannel": "Insiders",
"[makefile]": {
"editor.insertSpaces": true
},
"C_Cpp.default.includePath": [
"${workspaceFolder}"
],
"clang.completion.enable": true
}
Change this configuration to your needed Linux, that may be like:
{
"files.defaultLanguage": "c++",
"editor.suggest.snippetsPreventQuickSuggestions": false,
"editor.acceptSuggestionOnEnter": "off",
"code-runner.runInTerminal": true,
"code-runner.executorMap": {
"c": "cd $dir && gcc -std=c11 -stdlib=libc++ $dir/*.c -o $dir/$fileNameWithoutExt && $dir/$fileNameWithoutExt", // Have changed
"cpp": "cd $dir && g++ -std=c++11 -stdlib=libc++ $dir/*.cpp -o $dir/$fileNameWithoutExt && $dir/$fileNameWithoutExt" // Have changed
},
"code-runner.saveFileBeforeRun": true,
"code-runner.preserveFocus": false,
"code-runner.clearPreviousOutput": false,
"code-runner.ignoreSelection": true,
"C_Cpp.clang_format_sortIncludes": true,
"editor.formatOnType": true,
"clang.cxxflags": [
"-std=c++11"
],
"clang.cflags": [
"-std=c11"
],
"C_Cpp.updateChannel": "Insiders",
"C_Cpp.default.includePath": [
"${workspaceFolder}"
],
"clang.completion.enable": true
}
But I suggest that you may read Using C++ on Linux in VS Code.
END.
Open your tasks.json file and put the following in it:
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-g",
"${workspaceFolder}/*.c",
"${workspaceFolder}/*.h",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": [
"$gcc"
],
"group": "build"
},
{
"type": "cppbuild",
"label": "C/C++: gcc-8 build active file",
"command": "/usr/bin/gcc-8",
"args": [
"-fdiagnostics-color=always",
"-g",
"${workspaceFolder}/*.c",
"${workspaceFolder}/*.h",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
]
}
If you have any C++ source, add "${workspaceFolder}/*.cpp" too.
Note that if you haven't any of those files in your dir it gives you an error.
If you are using linux then know how to use make. If save a lot of time and effort. If you have even 10s or 100s of files and some dependencies are there then just make a Makefile once and every time you compile just use one command make and that will do all the work for you. Even you can make a keyboard shortcut for that command in VSCode.
Check out here to use make and here for using that in VSCode.
I had similar problem, and it was not easy to find answer which I fully understand. First thing you need to understand is that all .cpp files used in your project need to be compiled for the linker. for project with one .cpp file there is relatively no issue. you simply need to tell g++ which .cpp file need to be compiled by running the following command in the terminal from the root directory:
g++ -g main.cpp -o mainApp
This tells g++ to compile main.cpp an create a consolApp (output file) named mainApp.
In the case of a project with more than one .cpp file,
|--root
|--main.cpp}
|--include1
|-- foo1.h
|-- foo1.cpp
|-- include2
|-- foo2.h
|-- foo2.cpp
|-- foo3.cpp
To compile this project and build the output file we run this in the terminal:
g++ -g main.cpp include1/foo1.cpp include2/foo2.cpp foo3.cpp -o mainApp
Note that the order in which we pass the .cpp files to be compiled doesn't really matter.
You can already understand that for a very large project writing that command will be very tedious. you can rewrite is as follow
g++ -g ./*.cpp include1/*.cpp include2/*.cpp -o mainApp
This simply tells g++ to compile all .cpp file in the root, include1 and include2 folders.
What if your project has a lot of folders, you can simply run it recursively
g++ -g ./**/*.cpp -o mainApp
This is kind of telling g++ to go through root folder and through other folder and compile all .cpp files it will find.
To do the same thing in vscode, go to the tasks.json file, and in 'args' add :
"${workspaceFolder}/.cpp",
"${workspaceFolder}/**/.cpp",
This is the equivalent of :
g++ -g ./**/*.cpp -o mainApp
I had trouble to getting VS Code to compile multiple source files. It turned out to be that the workspace folder file path had a folder with a space in it. That space would cause the changed line to be read literally instead of looking for all .cpp files. I changed the path to have no spaces, and then it compiled successfully.
I only had to change one line in the tasks.json file:
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-fdiagnostics-color=always",
"-g",
"${workspaceFolder}/*.cpp", //changed line from "${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": "build",
"detail": "compiler: /usr/bin/g++"
}
]
}
'Adds single quotes'
I also had this problem on linux, and arrived at this solution based on some other answers and comments here.
Replacing the args parameter "${file}" in tasks.json with "${fileDirname}/*.cpp" will work for some of us - but only if there are no spaces in the resulting path string.
However, I have spaces in some of the directory names on the path to my working directory. So, when I use ${fileDirname} to get the directory string, there are spaces in the result.
The presence of spaces means this argument will automatically be surrounded in double quotes, becoming a literal string and also destroying our expected behaviour of the asterisk wildcard *. The compiler will simply be looking for a single file named *.cpp in that directory.
A set of single quotes around the relevant portion of the argument solves the problem (and I won't need to go removing all the spaces from my existing directory names).
And so: the argument "${fileDirname}/*.cpp" gains some single quotes and becomes "'${fileDirname}'/*.cpp" and everything works as expected.
tasks.json
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-g",
"'${fileDirname}'/*.cpp", // note the placement of the single quotes
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
// ... other json blocks ...
}
]
}
For those who are struggling with not working syntax like ${workspaceFolder}\**.cpp, ${workspaceFolder}/**.cpp, ${workspaceFolder}/*.cpp, etc., be sure to check also other parameters in tasks.json.
On my ArchLinux with VS Code 1.74.2, setting "type": "cppbuild" helped. So, my tasks.json looks like this:
{
"version": "2.0.0",
"tasks": [
{
// "type": "cppbuild", // Not working if commented out
"type": "cppbuild", // OK
"label": "Build with Clang++ (Linux)",
"command": "clang++",
"args": [
"-std=c++17",
"${fileDirname}/*.cpp",
"-o",
"${fileDirname}/${fileBasenameNoExtension}",
],
"options": {
"cwd": "${fileDirname}"
},
"group": {
"kind": "build",
"isDefault": true
},
},
]
}
It seems that VS Code wraps arguments in quotes for several reasons, also mentioned by others.