When executing any C program that I have compiled with gcc
from the terminal, I get a permission denied error.
To start, I have verified and repaired permissions on my drive (before doing this, the same problem was happening).
To illustrate and isolate the problem, I'll show you what happens with this ultra-simple Hello World program (with other programs, the same thing occurs):
#include <stdio.h>
main()
{
printf("Hello World");
}
Now, I save this to my desktop as helloworld.c
. At this point, from the desktop, an ls -l
returns:
total 8
-rw-r--r-- 1 michael staff 56 Mar 13 14:08 helloworld.c
I then compile with gcc -c helloworld.c -o helloworld
(I've also tried compiling without the -o
flag with the same results). No warnings or errors. An ls -l
now returns:
total 16
-rw-r--r-- 1 michael staff 56 Mar 13 14:08 helloworld.c
-rw-r--r-- 1 michael staff 724 Mar 13 14:16 helloworld.o
Attempting to execute the output of gcc, with ./helloworld.o
returns:
-bash: ./helloworld.o: Permission denied
Just for the sake of debugging, if I execute with sudo (sudo ./helloworld.o
), it returns:
sudo: ./helloworld.o: command not found
Now, if I attempt to set the executable flag using chmod +x helloworld.o
, as was recommended on a lot of search results I've found, ls -l
returns:
total 16
-rw-r--r-- 1 michael staff 56 Mar 13 14:08 helloworld.c
-rwxr-xr-x 1 michael staff 724 Mar 13 14:16 helloworld.o
However, attempting to execute with ./helloworld.o
now returns:
-bash: ./helloworld.o: Malformed Mach-o file
Now, for debugging sake, where gcc
returns:
/usr/bin/gcc
So, you can see that I am not using a third party gcc
.
Does anyone know what could be the problem? I've tried searching around, but I couldn't find any working solutions. I was having this same problem earlier and have since freshly reinstalled OS X (for different reasons) and am still having this problem with a clean and organized development environment. For reference, I'm on OS X 10.8.2 and have Xcode 4.6 along with the latest version of Xcode Command Line tools (from Apple's developer website). I have not installed gcc from Homebrew or from any other third party source; it is the gcc that came with Xcode Command Line tools.
Thank you very much for your help! I really appreciate you taking your time to read, diagnose and offer your help. :)
You're trying to execute object code (helloworld.o) rather than compile and link an executable binary. Don't use the -c
option. Run this instead:
$ gcc helloworld.c -o helloworld
It will be created with executable permissions. You can then run.
$ ./helloworld
as normal.
-c
option tells the compiler just to compile the file, but not link it. The link process is needed to create the final executable file. If you don't supply -c
, gcc will both compile and link for you behind the scenes.