JT9
JT9

Reputation: 944

How to compile and run C program on Mac OS X

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?

Upvotes: 39

Views: 92161

Answers (7)

Illia
Illia

Reputation: 11

But you forgot the dot,

./a.out

also you can just use cmake to compile your C program into binary if ./a.out doesn't work!

Upvotes: 1

Kent Aguilar
Kent Aguilar

Reputation: 5338

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

Upvotes: 0

MichaelM
MichaelM

Reputation: 488

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

Upvotes: 4

bee
bee

Reputation: 1623

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

Upvotes: 20

aFactoria
aFactoria

Reputation: 977

To build:

    gcc -Wall -o yourFile yourFile.c

Then to execute:

    ./yourFile

Upvotes: 6

DrummerB
DrummerB

Reputation: 40201

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.

Upvotes: 6

MByD
MByD

Reputation: 137272

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

Upvotes: 61

Related Questions