Cannot start program C: "a.out: command not found"

I wrote my first program in C. I compiled it, and it put a file on the desktop called a.out (since the book I read told me that it should), but when I type a.out command into the terminal and run it , he says -bash: a.out: command not found . Why is this so?

According to Stephen Cochan's book "C Programming", I am doing it right because I enter the correct directory (desktop), I think. He also says that if the file is not in the correct path, I can either add it to the path or run ./a.out , this method works and launches the program, why is this?

+12
terminal sh
source share
2 answers

When you enter a command name ( a.out is no different from any other command name in this regard), the shell looks for an executable file with that name. It performs this search using a list of directory names stored in the $PATH environment variable.

You can see your current $PATH by typing

 echo $PATH 

on the command line. A typical value might be something like

 /usr/bin:/bin 

although you will probably have additional directories.

Since a.out is in your current working directory (type pwd to see what that directory is), and your current working directory is probably not in your $PATH , you cannot execute it just by typing a.out .

Because you can link to your current directory as . , you can (and should) execute the command by typing

 ./a.out 

NOTE: you may have one . in your $PATH , but this is considered a bad idea, as it makes random commands too random. If . located in front of your $PATH , imagine I ask you to cd into my directory and type ls - but I installed a file called ls that does something unpleasant. The room . at the end of your $PATH reduces this risk, but does not completely eliminate it. It is best to develop the habit of adding a file name to ./ if you want to execute it from the current directory.

(I ignored the fact that aliases, functions, and shell built-in commands can also be executed this way.)

+23
source share

You need to enter ./a.out . This ./ tells bash to look for the a.out file in the current directory (dot - . - points to the current directory).

If you type a.out in bash without specifying a directory, it will look for it through the directories in the $PATH variable (if you are interested in seeing them, run echo $PATH ). Therefore, you can either tell him to run the file present in the current directory, or add the current directory (or desktop directory) to $PATH .

+6
source share

All Articles