I started with the easiest piece of code
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
I setup VScode to run C++ and this is tasks.json
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: gcc build active file",
"command": "/usr/bin/gcc",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
when I run the script I get
Starting build...
/usr/bin/gcc -fdiagnostics-color=always -g /Projects/c++/primo.cpp -o /Projects/c++/primo
/usr/bin/ld: /tmp/ccoasAow.o: warning: relocation against `_ZSt4cout' in read-only section `.text'
/usr/bin/ld: /tmp/ccoasAow.o: in function `main':
/Projects/c++/primo.cpp:5: undefined reference to `std::cout'
/usr/bin/ld: /Projects/c++/primo.cpp:5: undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
/usr/bin/ld: /tmp/ccoasAow.o: in function `__static_initialization_and_destruction_0(int, int)':
/usr/include/c++/11/iostream:74: undefined reference to `std::ios_base::Init::Init()'
/usr/bin/ld: /usr/include/c++/11/iostream:74: undefined reference to `std::ios_base::Init::~Init()'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
collect2: error: ld returned 1 exit status
Build finished with error(s).
* The terminal process terminated with exit code: -1.
* Terminal will be reused by tasks, press any key to close it.
I see there is an undefined reference to 'std::cout' but don't know how to solve it.
If I run the code in terminal, it works
Use g++
to compile C++, as gcc
is for C.