VS Code will not build c++ programs with multiple .ccp source files
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"
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
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.