-1

I am trying to learn C++, but I can't even make the first (hello world) example from cplusplus.org work with g++ command or c++. I created a file just like the example and ran g++ myfile, then ./myfile.

I get a permission problem, then I use chmod +x myfile and the permission problem is gone but this problem happens:

gzuspower@gzuspower:~/Desktop$ ./4
./4: line 1: //myfirst: No such file or directory
./4: line 4: syntax error near unexpected token `('
./4: line 4: `int main ()'

I called my file 4 because it is my 4th attempt. This is on Xubuntu 16.04.The duplicate question answer did not work i tried .c ,.cpp ,as file extension and tried firstc++ (my first attempt file) instead of 4(my fourth attempt file) and nothing works. i'm going to try different form of hello-world code.

7

What's Going Wrong

It is rarely useful to run chmod on a file you think your compiler has produced. When a compiler produces a binary file that is intended to be executed--that is, when it produces your program--it will automatically mark it executable. If you are able to successfully mark a file as executable with chmod +x--which you were--then your compiler will be able to do the same thing. If you try to run what you think is a program produced by your compiler, and you get an error about permissions, this usually means you are running the wrong file.

In this case, the specific error messages reveal that you are attempting to run your own C++ source code file. That will never work. You need to run the file produced by your compiler, which is a separate file. With most compilers, including g++, this file is called a.out unless you have passed a different output filename by passing -o filename as command-line arguments to the compiler. You should usually do that.

Also, if your C++ source code file is not named with a name that ends in .cpp, .cxx, .cc, or .C, then it should be. Furthermore, this is case sensitive. A file named ending in .c means C source code, not C++, and even when you run a C++-specific compiler command like g++, it will be treated as C. Most C++ compilers--including g++ and nearly all others that run on Ubuntu--will examine the suffix of your input files to figure out how to treat them. There are ways to explicitly tell your compiler what language your source code is written in, but they are cumbersome compared to simply naming your source code files in the conventional way.

Change Directory to Where You Saved Your Source Code File

You have written (or pasted in) some C++ code in a text editor and saved it in a file. First make sure that you have navigated to the directory where that file resides. In the terminal, you can use the cd command to change directory. When you open a terminal window, you are typically in your home directory. Suppose your source code file is called hello.cpp. Then running a command like g++ -o hello hello.cpp will only succeed if hello.cpp is actually located immediately in your home directory. If it is instead, for example, on your desktop, then first run:

cd ~/Desktop

(The ~/ part represents your home directory. If you are already there in your terminal, then you do not need to include that part. But I've included it, because that command will get you to the Desktop subdirectory of your home directory no matter where you already are.)

As another example, if you have a directory on your desktop called source and you have saved your source code file inside that directory, then you could get there in the terminal by running:

cd ~/Desktop/source

If you have folder icon in your file browser for the directory you want to go to, then you can get there by typing cd, typing a Space, and dragging that icon into your terminal window. That will copy its full pathname into the terminal and you can press Enter.

Once you have cded to wherever your source code file is located, check for it. For example, you could run this to list all the files in the current location (except files whose names start with ., which you likely don't want to see):

ls -l

Or you could pass the filename of your source code file to ls. For example, if it is called hello.cpp, then you can run:

ls -l hello.cpp

If, when you do that, you see this error, it means that there is no file by that name in the current directory:

ls: cannot access 'hello.cpp': No such file or directory

So if you see an error message like that, then don't try to compile your program with the g++ or c++ command anyway, because it will not work, because you are not in the right place.

Try to Compile Your Source Code, and See If There Are Errors

Once you know you are in the right place, try to compile your source code file, and see if the compiler reports anything it calls an error. Once you've successfully compiled and run your first program, you should start heeding compiler warnings, too, because they often tell you valuable information about problems in your code. They can also help explain errors. However, it is important to understand the difference between an error and a warning. Even though none of the documents that standardize C++ have actually talked about errors or warnings as such (they talk about "diagnostics"), the distinction is of great importance. An error is the compiler telling you that it can't compile your program.

Here's an example of a compile error you might see:

hello.cpp:55:84: error: expected primary-expression before ‘<<’ token

Notice that the compiler includes error: in the message. Look for that. You may get many different kinds of errors, depending on your source code and how you are using your compiler. They will not all look quite like that. But they will typically say error:.

If you attempt to compile your program, but the compiler produces something it calls an error, and you ignore this and attempt to run your program, then there are three possibilities and none of them is what you want. You could be running something that your compiler did not produce. This happened to you: you tried to run your source code file itself. Or you could be trying to run a file that doesn't even exist. Or you could be running something your compiler previously produced during an earlier compilation that was successful, and thus running an older version of your program than you mean to run.

With that in mind, you can attempt to compile your program by running a command like this one:

g++ -o hello hello.cpp

I say that you would run a command like that one because you will need to change hello.cpp to the actual name of your C++ source code file. You may also want to change the hello that appears after -o to some other filename. This filename is the program the compiler will produce if it succeeds, that is, if there are no errors. You will probably not want to call all your programs hello. If there is already a file in the current directory called hello, or whatever you put instead of it after -o, then the compiler will overwrite that file.

If there were errors then it is time to try to figure out what went wrong. Maybe there is a mistake in the source code. Maybe you made a mistake compiling it. Maybe it requires more options to be passed to the compiler. There are a lot of things that can go wrong, and while you will likely be able to figure it out most of the time, you may sometimes--perhaps even often--need to ask for help, which is fine. When you do ask for help, you should always make sure to provide the complete source code of a small program that produces the problem and completely describe everything you have done and what happened, including showing all the commands you ran and their output.

Try To Run Your Program And See What Happens

Suppose you passed -o hello to the compiler as shown above, and the compilation succeeded. Then you would attempt to run your program with the command:

./hello

If you see an error like this, then it means your program is not found:

bash: ./hello: No such file or directory

So if that happens, look back at the output from the compiler. Check if perhaps there were errors that you missed. Similarly, if you see an error like this, then it means that the file you are trying to run does exist, but cannot actually be run. There are multiple possible causes of this problem, but usually it means that you are trying to run the wrong file:

bash: ./hello: Permission denied

Before, I described using ls -l to see what files are in the current directory, or to check for particular files. The context was checking if you are in the right place to start trying to compile your program. But after you have compiled your program, if you cannot run it and you are not sure why, then the ls command is one of the tools you can use to see if the compiler ever actually created the file.

One of the things running ls -l (or perhaps just ls) may sometimes help you discover is if you mistyped the name, and accidentally wrote something different after -o (when you compiled the program) than what you wrote after ./ when you tried to run the program.

The purpose of the ./ in ./hello is to tell your shell that you want to run a file called hello that is located in the current directory. . stands for the current directory. If you were to just write hello and press Enter, without the leading ./, then the shell would try to look up and run a command called hello that is installed. That's not what you want, here. You want to run the specific file you just compiled and that resides in the current directory.

What You Saw

Finally, suppose you attempt to run your program and you see messages that contain fragments of its source code, like this, which you did see:

./4: line 1: //myfirst: No such file or directory

I haven't even seen your source code, but I can tell that this looks like it contains a fragment of it. Specifically, //myfirst looks like the beginning of a single-line comment that you may have placed at the top of your source code. Although it possible to try to run a program and have problems that show messages containing text from your source code file, this is rare. What is far more common is that you have accidentally attempted to run your source code file instead of your the binary file produced by the compiler! So if you see error messages when you run a C++ program that look like they are mentioning pieces of your source code, always check for that. And when you attempt to run a C++ program, always run the file that your compiler produced, which is not the same as the source code file you wrote yourself.

An entire answer could (and hopefully will) be written about exactly why you saw those specific messages. Basically, though, what happened was that your used chmod to make your source code file executable, and then when you ran it, it was run as a shell script. The code //myfirst was interpreted as code in a shell (bash, in this case) instead of C++, where it told the shell to try to run a file called my myfirst in the / directory. There was no such file, so you got an error.

Speaking more generally, though, I recommend keeping mind:

  • If your compiler said something that it called an "error" then it is unlikely that it created your program.
  • If you attempt to run your program and you see output that makes no sense at all, especially if that output contains messages that seem to mention parts of your source code, then double check that your program was really created and that you are running it, and not running your source code file, or some other file, or some other program.
3

You are calling the compiler incorrectly. You should also use the .cc or .cpp file extension for C++ files. The correct incantation of the compiler command there would be for example g++ hello-world.cpp -o hello-world.

  • I tried the compiler command u suggested, this was the outcome gzuspower@gzuspower:~/Desktop$ g++ firstc++.cpp -o firstc++ g++: error: firstc++.cpp: No such file or directory g++: fatal error: no input files compilation terminated. The name of my file was firstc++ when i right-click it and go to properties the kind states it is C source code. – Steve Wooten Apr 14 '18 at 10:03
  • 3
    @SteveWooten Please edit your question. Paste complete text of each C++ program you've tried to compile, and complete text from the terminal: what you typed in and the output you got, each time you tried to compile and run it. (If necessary, at least reproduce the problem at least once and provide the information from that.) Although I'm confident that this question was wrongly closed, and that another answer is already possible (unless it gets wrongly reclosed before anyone can post one), it's likely that no answer will fully satisfy you if you do not include all the relevant details. – Eliah Kagan Apr 14 '18 at 19:48
2

As explained in this answer by Eliah Kagan, the error messages you saw happened because you tried to execute your source file. Here I will attempt to explain why you got those particular messages.

When you give a file execute permission and then you try to execute it by running /path/to/filename (which is often ./filename), and it is a text file, it will be run as a script. Scripts normally have a shebang line as their first line, consisting of #! followed immediately by the full path of the intended interpreter.

When you try to run an executable text file from a Bash shell, and the file doesn't have a shebang line, Bash will assume it is a shell script and starts a new Bash shell to run it. (It's still a good idea to write #!/bin/bash at the top of a Bash script, in case the shell that runs it is not Bash.) But if the file contains something other than Bash code, then you'll usually get numerous syntax errors. That's what happened to you, as the error messages you got indicate:

$ ./4
./4: line 1: //myfirst: No such file or directory
./4: line 4: syntax error near unexpected token `('
./4: line 4: `int main ()'

When a shell tries to execute a file as a shell script, it spawns a new, non-interactive shell to interpret the script. That way, many things scripts might do, like changing directory or defining variables or functions, won't have any effect on the calling shell. We can test how a non-interactive child shell like the one that tried to run your source file behaves by sending input to to bash with here strings, like this:

$ bash <<< 'echo Hello World!'
Hello World!

Just running the command in the current shell would produce the same or similar output a lot of the time (for example in the above case), but we can reproduce your error messages more accurately this way. For example:

$ bash <<<'//myfirst C++ program'
bash: line 1: //myfirst: No such file or directory

I made a guess about what line 1 of your source file said based on the error. //, which starts a single-line comment in C++, isn't a comment in Bash. If the first word of a command has a / in it, Bash takes that word to be a path. If the path were that of an executable file, the file would be executed. (That's exactly what happened when you ran ./4: the file whose path was ./4 was executed.) If there's no such file, then we get an error message saying so.

// resolves to the root directory /, and since it didn't contain a file called myfirst on your system, you got that No such file or directory. If it had contained a matching file you would probably have got a different error:

$ bash <<< '/dev'
bash: line 1: /dev: Is a directory           # matches, but it's a directory
$ bash <<< '/swapfile'
bash: line 1: /swapfile: Permission denied   # matches, but not executable

Another style of comment you might have used in a C++ program, /* */, could have produced more interesting or chaotic results, since /* would expand to all non-hidden files in the root directory, and */ would expand to all non-hidden files that are directories in the current directory.

You didn't get any errors about line 2 or 3. This might be because they were empty, or because they contained some valid Bash code (very unlikely) that produced no output, or they had a line that began with #, which is a comment in Bash. For example, you might have had a line like:

#include <iostream>

As Bash runs commands from a file, it assumes anything beginning with an unquoted # is just for humans and ignores it.

Then on line 4 you got a syntax error:

$ bash <<< 'int main()'
bash: line 1: syntax error near unexpected token `('
bash: line 1: `int main()'

( and ) are shell metacharacters and control operators. They may spawn a subshell in which a command or list of commands can be run. A common use of this is command substitution where the output of the command run in the subshell replaces it in the outer shell. This happens when $ precedes (stuff). Here's a (useful) example:

$ which g++
/usr/bin/g++
$ readlink -e $(which g++)
/usr/bin/x86_64-linux-gnu-g++-7

Double parentheses cause arithmetic expansion:

$ bash <<< 'echo $((3+4))'
7

Another use of () is to indicate that the preceding word is a function being defined, as explained in answers to What's the use of parentheses `()` in shell function definition? If there are two words before () in a command, unless the first word is function, ( will be a syntax error:

$ bash <<< 'foo bar()'
bash: line 1: syntax error near unexpected token `('
bash: line 1: `foo bar()'
$ bash <<< 'function bar()'
bash: line 2: syntax error: unexpected end of file

function is optional and we get the same error without it. The EOF error occurs because we haven't gone on to define the function.

When a shell encounters a syntax error, it will stop processing the current input (and if it is a non-interactive shell, immediately exit) so you won't see any further errors no matter what follows. Whatever your source file went on to say after int main(), the shell didn't read it.

Many thanks to Eliah Kagan for encouraging me to write this answer and providing various helpful insights!

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.