Search code examples
c++unixgistnano

C++ compiler command c++ does not generate output


I have written a C++ file in nano text editor (UNIX command line) and I am trying to execute it with this command: c++ main.cpp. When I run it, no error messages display, however, there's also no successful messages; simply nothing appears... I also tried clang which gave me some more details, click here to view the error message. My code:

#include <iostream>

using namespace std;

int main() {
    cout << "Hello" << endl;

    return 0;
}

Clang Output:

/usr/bin/ld: /tmp/main-ad7332.o: in function `main':
main.cpp:(.text+0x11): undefined reference to `std::cout'
/usr/bin/ld: main.cpp:(.text+0x24): 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: main.cpp:(.text+0x2d): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
/usr/bin/ld: main.cpp:(.text+0x36): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
/usr/bin/ld: /tmp/main-ad7332.o: in function `__cxx_global_var_init':
main.cpp:(.text.startup+0x13): undefined reference to `std::ios_base::Init::Init()'
/usr/bin/ld: main.cpp:(.text.startup+0x19): undefined reference to `std::ios_base::Init::~Init()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Solution

  • No output whatsoever is the expected outcome. Running c++ only compiles the provided source file. To run your program, you will have to explicitly run the produced executable, which by default is a.out.

    With regards to the error messages you received from clang, make sure that you are using clang++ and remembered to include the iostream header, which declares std::cout.