Search code examples
c++ubuntuterminalgedit

Running C++ file on Terminal in Ubuntu


I'm new to C++.
I've created a C++ file with gedit in Ubuntu. But when I tried to run it on terminal, it says

no such file or directory

When I typed ls on Terminal, it shows that the c++ file was not created at all.

Where did I go wrong?

  1. saved a file with .cpp with gedit on my desktop.
  2. Went to terminal and typed something like g++ -o test file name.cpp.
  3. I was then shown an error message of “no such file or directory”.

This is my code:

#include <iostream>

using namespace std;

int main()
{
   cout << "Hello World\n";
   return 0;
}

Solution

  • First you have to find the directory where you saved the source file from gedit. File->Save As is one place which shows the directory, and there probably is also some "file properties" action in that menu which also shows the path. In command line use cd to move to that directory before running your compilation command.

    You can use ls to see if the directory contains the files you expect, as you have done. pwd is useful for showing the full path of your current working directory. In general, it would be very useful if you did a Linux terminal tutorial or two, to get the hang of working on unix terminal command line.


    Then it looks like you have spaces in your file name here: g++ -o test file name.cpp It is a bit unclear which is which, but I presume you want this:

    g++ -o test 'file name.cpp'
    

    In unixy terminals, the shell (you probably have bash) is responsible for splitting the command line arguments, and this by default happens at whitespaces. If you have white space in single argument (like the file name here), you have to make it so that shell doesn't split that argument into two. There are several ways to do it, single quotes like above is just one, but it is a broad subject and way beyond this answer.