-1

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

2
  • 8
    Use g++ to compile C++ programs, not gcc. Commented Mar 20 at 15:37
  • Minor pont: technically, the last line of console output must end with a newline character, so std::cout << "Hello, World!\n";. In practice, this just ends up showing your command-line prompt on the same line as your output. In olden days on some mainframes it made more of a difference. Commented Mar 20 at 16:29

1 Answer 1

3

Use g++ to compile C++, as gcc is for C.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.