35

I am learning C and wish to write the program using a text editor on my Mac (running OS X v10.7 (Lion)).

I write the .c file, and compile it using gcc filename.c - which creates executable file called a.out. However, when I type a.out or /a.out, I get the following messages:

-bash: a.out: command not foundor-bash: /a.out:
No such file or directory

I have successfully compiled and ran C programs on Linux systems before using this same method. What am I doing wrong on my Mac?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
JT9
  • 874
  • 5
  • 13
  • 22
  • The canonical question is *[How can I compile and run C/C++ code in a Unix console or Mac terminal?](https://stackoverflow.com/questions/221185/)*. – Peter Mortensen May 08 '22 at 13:45

6 Answers6

56

You need to add a dot to indicate that the executable is in the current directory, as the current directory is not in the path:

./a.out
MByD
  • 133,244
  • 25
  • 260
  • 270
  • 3
    @JTWheeler, you might also consider naming your object file as this would prevent a.out from being overwritten when compiling multiple C programs manually in the same directory. Do `gcc myprog1.c -o myprog1.o` and run it by doing `./myprog1.o`. Just a suggestion. And alternatively you could use clang instead of gcc for you practice code as it gives better error details. – Bharat Dec 15 '12 at 00:08
17

You need to precede a.out with ./ as follows:

./a.out

Additionally, you may find it useful to change the name of the resultant executable. Example:

gcc nameofprogramyouwrote.c -o whatyouwanttheprogramtobenamed

...then execute it like this:

./whatyouwanttheprogramtobenamed
user664833
  • 16,967
  • 18
  • 88
  • 129
beckah
  • 1,482
  • 5
  • 26
  • 57
5

You have to add a dot in front of the slash:

./a.out

/a.out would try to execute a program in the root folder (/).
a.out will look for your program in all the folders defined in the PATH environment variable.

I have successfully compiled and ran C programs on Linux systems before using this same method. What am I doing wrong on my Mac?

You have to do the same on Linux.

DrummerB
  • 39,275
  • 12
  • 103
  • 141
4

To build:

    gcc -Wall -o yourFile yourFile.c

Then to execute:

    ./yourFile
aFactoria
  • 817
  • 1
  • 7
  • 7
3

Make sure to set your permissions executable with chmod +x a.out.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
MichaelM
  • 477
  • 1
  • 5
  • 16
-1

You'll need a compiler. The easiest way, however, is to install Xcode. This way you'll get access to GCC.

Thus,

gcc -o mybinaryfile mysourcefile.c

Then run it like this.

./mybinaryfile
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Kent Aguilar
  • 4,420
  • 1
  • 31
  • 20